Here's a step-by-step guide on how to build a Docker image from a Dockerfile and then run it as a container:
Step 1: Write the Dockerfile
Ensure your Dockerfile is ready. Below is an example:
Use a base image
FROM node:14
Set the working directory inside the container
WORKDIR /app
Copy package.json and package-lock.json to the container
COPY package*.json ./
Install dependencies
RUN npm install
Copy the rest of the application code
COPY . .
Expose the port the app runs on
EXPOSE 3000
Command to run the app
CMD ["node", "index.js"]
Step 2: Build the Docker Image
Run the following command in the directory where your Dockerfile is located:
docker build -t your-image-name .
-t your-image-name: Tags the image with the name your-image-name.
.: Specifies the current directory as the build context.
Step 3: List Docker Images
To verify if your image has been created, use:
docker images
Step 4: Run a Docker Container
Once your image is built, you can run a container based on that image:
docker run -d -p 3000:3000 --name your-container-name your-image-name
-d: Runs the container in detached mode (in the background).
-p 3000:3000: Maps port 3000 on your local machine to port 3000 on the container.
--name your-container-name: Names the container for easier reference.
your-image-name: The name of the image you built earlier.
Step 5: Verify Running Containers
To see if your container is running:
docker ps
Step 6: Stop the Container
To stop the running container:
docker stop your-container-name
Step 7: Remove the Container (Optional)
If you want to remove the container:
docker rm your-container-name
Step 8: Remove the Docker Image (Optional)
To delete the image:
docker rmi your-image-name
These commands outline the general flow of creating Docker images from a Dockerfile, running containers, and managing them.