Docker and docker compose cheat sheet
Docker engine CLI commands
Basic commands
docker --version: Check Docker version.docker ps: List running containers.docker ps -a: List all containers (including stopped).docker images: List all Docker images.docker pull <image>: Download an image from Docker Hub.docker run <image>: Run a container from an image.-d: Run in detached mode.-p <host_port>:<container_port>: Map host to container port.--name <name>: Name the container.
Container Management
docker stop <container>: Stop a running container.docker start <container>: Start a stopped container.docker restart <container>: Restart a container.docker rm <container>: Remove a container.docker logs <container>: View logs of a container.docker exec -it <container> <command>: Execute a command inside a running container.- Example:
docker exec -it my_container bash.
- Example:
Image Management
docker build -t <tag> .: Build an image from a Dockerfile in the current directory.docker tag <image> <repo>:<tag>: Tag an image for a repository.docker push <repo>:<tag>: Push an image to a repository.docker rmi <image>: Remove an image.
Volume & Network
docker volume create <name>: Create a volume.docker volume ls: List volumes.docker network create <name>: Create a network.docker network ls: List networks.
System Cleanup
docker system prune: Remove unused containers, images, networks, and volumes.docker image prune: Remove unused images.
Dockerfile
Key instructions:
FROM: Specify the base image.- e.g:
FROM image_name:tag
- e.g:
LABEL: Metadata for the image (e.g., maintainer info).WORKDIR: Set the directory for commands likeRUN,CMD,ENTRYPOINT.- e.g:
WORKDIR /app
- e.g:
COPY: Copies files from host to container.- e.g:
COPY requirements.txt /app/
- e.g:
ADD: Similar toCOPY, but can also extract archives.RUN: Execute commands to install dependencies or configure the container.- e.g:
RUN apt-get update && apt-get install -y python3
- e.g:
CMD: Default command to run when the container starts.- e.g:
CMD ["python3", "app.py"]
- e.g:
ENTRYPOINT: Similar toCMD, but allows passing additional arguments at runtime.EXPOSE: Document the port on which the container listens (doesn't publish the port).ENV: provides ability to set env variable inside container.- e.g:
ENV APP_ENV=production
- e.g: