G: Ever felt lost in the sea of Docker commands while trying to deploy your applications? You’re not alone! Docker has become an indispensable tool for developers and DevOps engineers, simplifying the process of building, shipping, and running applications. But with great power comes a plethora of commands and options.
This comprehensive cheat sheet is designed to be your go-to resource for the most frequently used Docker commands and their essential options in real-world scenarios. We’ll break down the commands into logical categories, provide clear examples, and highlight the practical tips you need to master Docker. Let’s dive in! β¨
I. Getting Started: The Basics of Docker Lifecycle ποΈ
These are the fundamental commands you’ll use daily to interact with Docker images and containers.
1. docker pull
: Fetch an Image from a Registry β¬οΈ
Before you can run a container, you need an image. docker pull
downloads images from Docker Hub or a private registry.
- Basic Usage: `docker pull
[: ]` * `docker pull ubuntu`: Downloads the `latest` tag of the `ubuntu` image. * `docker pull nginx:1.21`: Downloads a specific version of Nginx. - Practical Tip: Always specify a tag to ensure reproducible builds, especially in production environments.
latest
can change unexpectedly!
2. docker run
: Create and Start a Container πββοΈ
This is arguably the most crucial Docker command. It creates a new container from an image and runs a command inside it.
-
Basic Usage: `docker run
` * `docker run hello-world`: Runs the classic “Hello World” example. * `docker run ubuntu echo “Hello from Ubuntu!”`: Runs a simple command in an Ubuntu container. -
Key Options for Practical Use:
-d
,--detach
: Run container in detached mode (in the background). Your terminal won’t be blocked.docker run -d nginx
: Starts an Nginx web server in the background.
-p
, `–publish: `: Publish a container’s port to the host. Essential for accessing web apps. * `docker run -d -p 8080:80 nginx`: Maps port 80 (inside container) to port 8080 (on your host machine). Now access Nginx via `http://localhost:8080`. -it
,--interactive --tty
: Run container in interactive mode with a pseudo-TTY. Useful for shell access.docker run -it ubuntu bash
: Opens a Bash shell inside a new Ubuntu container.
- `–name
`: Assign a custom name to your container. Makes it easier to refer to later. * `docker run -d –name my_web_server -p 80:80 nginx`: Creates a named Nginx container. --rm
: Automatically remove the container when it exits. Great for temporary tasks or CI/CD pipelines.docker run --rm ubuntu echo "Temporary task done!"
: Container is cleaned up after the command finishes.
-v
, `–volume: `: Mount a host path or named volume into the container. (More details in Section IV) * `docker run -d -p 80:80 -v $(pwd)/html:/usr/share/nginx/html –name local_nginx nginx`: Mounts a local `html` folder to Nginx’s web root. - `–network
`: Connect the container to a specific Docker network. (More details in Section V) * `docker run -d –network my_app_network –name my_backend my_api_image`
3. docker ps
: List Running Containers π
See which containers are currently active on your system.
- Basic Usage:
docker ps
- Key Options:
-a
,--all
: Show all containers, including stopped ones.docker ps -a
-q
,--quiet
: Only display container IDs. Useful for scripting.docker ps -aq
: Get IDs of all containers (running and stopped).
--filter "status=exited"
: Filter by status, name, image, etc.docker ps --filter "name=my_web_server"
4. docker stop
, docker start
, docker restart
: Manage Container State π¦
Control the lifecycle of your containers.
- `docker stop
`: Gracefully stops a running container. * `docker stop my_web_server` - `docker start
`: Starts a stopped container. * `docker start my_web_server` - `docker restart
`: Stops and then starts a container. * `docker restart my_web_server`
5. docker rm
: Remove a Container β
Delete one or more containers.
- Basic Usage: `docker rm
` * `docker rm my_old_container` - Key Option:
-f
,--force
: Force removal of a running container. Use with caution!docker rm -f my_stuck_container
- Practical Tip: To remove all stopped containers (very common for cleanup):
docker rm $(docker ps -aq --filter "status=exited")
- Even better:
docker container prune
(See Section VII for cleanup commands!)
II. Image Management: Building & Handling Images π¦
Images are the blueprints for your containers. These commands help you create, list, and manage them.
1. docker build
: Build an Image from a Dockerfile π οΈ
This command reads a Dockerfile
to create a custom Docker image.
- Basic Usage: `docker build -t
[: ] ` * `docker build -t my_app:1.0 .`: Builds an image tagged `my_app:1.0` using the `Dockerfile` in the current directory (`.`). - Key Options:
-t
,--tag
: Assign a name and tag to the image.--no-cache
: Build image without using cache. Useful for ensuring fresh dependencies.docker build --no-cache -t my_app:latest .
--platform linux/amd64
orlinux/arm64
: Specify the platform if building for different architectures (e.g., Apple Silicon Macs building for Linux servers).--pull
: Always attempt to pull a newer version of the base images.
2. docker images
: List Images πΌοΈ
See all images stored on your local Docker daemon.
- Basic Usage:
docker images
ordocker image ls
- Key Option:
-a
,--all
: Show all images, including intermediate layers.--filter "dangling=true"
: Find “dangling” images (untagged layers that are no longer used).docker images -f "dangling=true"
(Often precursors todocker image prune
)
3. docker rmi
: Remove an Image ποΈ
Delete one or more images from your local store.
- Basic Usage: `docker rmi
` * `docker rmi my_old_app:1.0` - Key Option:
-f
,--force
: Force removal even if the image is used by a container.docker rmi -f old_image_in_use
- Practical Tip: To remove all dangling images:
docker rmi $(docker images -f "dangling=true" -q)
- Even better:
docker image prune
(See Section VII for cleanup commands!)
4. docker history
: Show Image Layers π
Displays the history of an image, showing each layer and the command that created it. Useful for debugging large image sizes.
docker history my_app:1.0
5. docker inspect
: Get Detailed Info π
Provides low-level information about Docker objects (images, containers, volumes, networks).
docker inspect nginx:latest
(for an image)docker inspect my_web_server
(for a container)- Practical Tip: You can use
--format
to extract specific pieces of information.docker inspect --format='{{.Config.Cmd}}' my_app:latest
: Get the default command of an image.docker inspect --format='{{.NetworkSettings.IPAddress}}' my_container
: Get the IP address of a container (if not using custom networks, prefer service names).
6. docker push
: Push an Image to a Registry β¬οΈ
Share your custom images by pushing them to Docker Hub or a private registry.
- Basic Usage: `docker push
/ : ` * `docker push myregistry.com/my_org/my_app:1.0` - Before pushing: You usually need to log in to the registry first.
docker login
docker logout
III. Container Management: Interacting with Running Containers βοΈ
Once your containers are running, you’ll need these commands to peek inside, execute commands, or copy files.
1. docker exec
: Run a Command Inside a Running Container π
This is incredibly powerful for debugging or running one-off commands within an active container.
- Basic Usage: `docker exec
` * `docker exec my_web_server ls -l /usr/share/nginx/html`: Lists files in Nginx’s web root. - Key Options:
-it
,--interactive --tty
: For interactive shell access.docker exec -it my_backend_app bash
: Opens a Bash shell in your backend container. This is extremely useful for troubleshooting!
-u
, `–user`: Run the command as a specific user inside the container. * `docker exec -u root my_container apt update`
2. docker logs
: View Container Logs π
Access the standard output and standard error streams of a container. Essential for monitoring and debugging.
- Basic Usage: `docker logs
` * `docker logs my_web_server` - Key Options:
-f
,--follow
: Stream new logs as they appear (liketail -f
).docker logs -f my_backend_app
- `–tail
`: Show only the last N lines of logs. * `docker logs –tail 50 my_app` -t
,--timestamps
: Add timestamps to log entries.docker logs -t my_app
3. docker cp
: Copy Files/Folders to/from a Container βοΈ
Transfer files between your host machine and a running container.
- Copy from host to container: `docker cp
: ` * `docker cp ./my_config.conf my_app:/etc/my_app/config.conf` - Copy from container to host: `docker cp
: ` * `docker cp my_db_container:/var/lib/mysql/dump.sql ./backup/dump.sql`
4. docker commit
: Create a New Image from a Container’s Changes πΈ
Saves the current state of a container as a new image. Less common in modern CI/CD, but useful for quick snapshots or debugging.
- `docker commit
: ` * `docker commit my_debug_container my_app_fixed:1.0`
5. docker rename
: Rename a Container βοΈ
Change the name of an existing container.
docker rename old_name new_name
IV. Data Management: Persistent Storage with Volumes πΎ
Containers are ephemeral by default. Volumes provide a way to store data persistently, independent of the container’s lifecycle.
1. Why Volumes? π€
- Persistence: Data survives container deletion.
- Sharing: Data can be shared between multiple containers.
- Performance: Can be more performant than bind mounts for I/O heavy operations.
2. Types of Mounts with docker run -v
The -v
or --mount
flag is used to attach storage.
- Named Volumes (Recommended): Docker manages the location on the host. Ideal for databases and application data.
- Create a named volume:
docker volume create my_data_volume
- List volumes:
docker volume ls
- Inspect a volume:
docker volume inspect my_data_volume
- Use in
docker run
:docker run -d -v my_data_volume:/app/data --name my_db_app postgres
- This mounts the
my_data_volume
to/app/data
inside the container.
- This mounts the
- Create a named volume:
- Bind Mounts: You directly control the exact mount point on the host. Useful for development (code changes immediately reflected) and configuration files.
docker run -d -p 3000:3000 -v $(pwd):/app --name my_node_app node:latest npm start
- Mounts your current host directory (
$(pwd)
) to/app
inside the Node.js container. - On Windows, use
%cd%
instead of$(pwd)
in PowerShell, or provide the full path.
- Mounts your current host directory (
--tmpfs
: Mount a temporary file system (RAM). Data is not persistent and is removed when the container stops. Useful for sensitive data or temporary cache.docker run -d --tmpfs /tmp/cache my_app
V. Networking: Connecting Your Containers π
Docker’s networking allows containers to communicate with each other and the outside world.
1. Default Bridge Network (bridge
)
When you don’t specify a network, containers attach to the default bridge
network. Containers on this network can communicate by IP address, but not easily by name.
2. Custom Bridge Networks (Recommended for Multi-Container Apps) π
Create your own bridge networks for better isolation and easy name-based resolution.
- Create a network: `docker network create
` * `docker network create my_app_network` - List networks:
docker network ls
- Inspect a network:
docker network inspect my_app_network
- Connect containers to a network:
- At
docker run
:docker run -d --network my_app_network --name my_web_app my_web_image
docker run -d --network my_app_network --name my_db postgres
- Now,
my_web_app
can communicate withmy_db
simply by using the hostnamemy_db
. No need to find IP addresses! π
- Connect an existing container: `docker network connect
` * `docker network connect my_app_network existing_container`
- At
- Disconnect a container: `docker network disconnect
`
VI. System & Troubleshooting: Keeping Docker Healthy π©Ί
Commands to check Docker’s status, resources, and system-wide information.
1. docker info
: Display System-Wide Information βΉοΈ
Shows details about your Docker installation, including containers, images, storage, and more.
docker info
2. docker version
: Show Docker Version Information βοΈ
Displays the Docker client and server (daemon) versions. Useful for compatibility checks.
docker version
3. docker events
: Get Real-time Events from the Server π
Streams events from the Docker daemon (e.g., container starts, stops, image pulls).
docker events
docker events --filter 'type=container'
(Filter for specific event types)
4. docker stats
: Display a Live Stream of Container Resource Usage π
Shows CPU, memory, network I/O, and disk I/O for running containers. Like top
for Docker!
docker stats
docker stats --no-stream
(Show current stats once)- `docker stats
` (Show stats for specific containers)
5. docker system df
: Show Docker Disk Usage π
Summarizes the disk space used by Docker images, containers, and volumes.
docker system df
VII. Cleanup: Freeing Up Space π§Ή
Docker can consume a lot of disk space with old images, stopped containers, and unused volumes. These commands help you reclaim space efficiently.
1. docker system prune
: The Ultimate Cleanup Command! β¨
This command removes all unused Docker objects. Use with caution, but it’s incredibly effective for freeing up space.
- Basic Usage (removes stopped containers, dangling images, unused networks):
docker system prune
- Remove all (including volumes):
docker system prune --all --volumes
ordocker system prune -a -v
- Note: This will remove all volumes not attached to at least one container. If you have named volumes you want to keep that aren’t currently attached, be careful!
- Force without confirmation:
docker system prune -f
2. Specific Prune Commands for Granular Control ποΈ
If you want to clean up specific types of Docker objects, use these commands:
- Containers:
docker container prune
(Removes all stopped containers) - Images:
docker image prune
(Removes dangling images)docker image prune -a
(Removes all unused images, not just dangling ones)
- Volumes:
docker volume prune
(Removes all unused local volumes) - Networks:
docker network prune
(Removes all unused networks)
VIII. Bonus: Docker Compose for Multi-Container Apps π
While this cheat sheet focuses on single-container docker
commands, for real-world applications with multiple services (e.g., a web app, a database, a cache), Docker Compose is indispensable. It simplifies the definition and management of multi-container Docker applications using a YAML file.
- Key Docker Compose Commands:
docker-compose up
: Build, create, and start services defined indocker-compose.yml
.docker-compose up -d
: Run services in detached mode.docker-compose up --build
: Rebuild images before starting services.
docker-compose down
: Stop and remove containers, networks, and volumes defined in thedocker-compose.yml
.docker-compose ps
: List containers for the current project.docker-compose logs
: View log output from services.docker-compose logs -f
: Follow log output.
- `docker-compose exec
`: Execute a command in a running service container. * `docker-compose exec web_app bash`: Get a shell into your web app container.
Conclusion: Master Docker, Master Your Workflow! π‘
You’ve just armed yourself with a powerful arsenal of Docker commands and essential options! From building and running containers to managing data, networks, and cleaning up your system, these commands are your daily drivers in the Docker ecosystem.
Remember, the best way to truly master these commands is to practice. Fire up your terminal, experiment with different options, and see how they impact your containers. The Docker documentation is also an excellent resource for deeper dives into any command.
Keep learning, keep building, and happy containerizing! π You’re now better equipped to navigate the world of Docker and streamline your development and deployment workflows. π