A Guide to Docker file and Useful Docker Commands.
Docker has revolutionized the way software is developed, deployed, and managed. With Docker, you can package your application and its dependencies into a standardized unit called a container, ensuring consistency across different environments. In this guide, we'll delve into Dockerfile, a crucial component for building Docker images, and explore some essential Docker commands to streamline your container workflow.
Understanding Dockerfile
Dockerfile is a text document that contains instructions for building a Docker image. It defines the environment inside the container, including base image, dependencies, environment variables, and more. Let's break down some essential components of a Dockerfile:
1. Base Image:
dockerfileCopy codeFROM ubuntu:latest
This instruction specifies the base image for your container. You can choose from a variety of base images available on Docker Hub, such as Ubuntu, Alpine, CentOS, etc.
2. Working Directory:
dockerfileCopy codeWORKDIR /app
Sets the working directory inside the container where subsequent instructions will be executed.
3. Copying Files:
dockerfileCopy codeCOPY . .
Copies files from your local directory into the container's filesystem.
4. Installing Dependencies:
dockerfileCopy codeRUN apt-get update && apt-get install -y \
python3 \
python3-pip
Installs dependencies inside the container using package managers like apt-get or pip.
5. Exposing Ports:
dockerfileCopy codeEXPOSE 8080
Specifies which ports should be exposed by the container.
6. Running Commands:
dockerfileCopy codeCMD ["python3", "app.py"]
Defines the command to run when the container starts.
🛠️ Useful Docker Commands
1. Building an Image:
bashCopy codedocker build -t myapp .
Builds a Docker image from the Dockerfile in the current directory and tags it as 'myapp'.
2. Running a Container:
bashCopy codedocker run -d -p 8080:8080 myapp
Runs a container from the 'myapp' image in detached mode (-d) and maps port 8080 on the host to port 8080 in the container.
3. Viewing Running Containers:
bashCopy codedocker ps
Lists all running containers along with their IDs, names, and other details.
4. Stopping a Container:
bashCopy codedocker stop <container_id>
Stops a running container specified by its ID.
5. Removing Containers/Images:
bashCopy codedocker rm <container_id>
docker rmi <image_id>
Removes a container and an image respectively, specified by their IDs.
6. Viewing Container Logs:
bashCopy codedocker logs <container_id>
Displays the logs of a specific container.