G: Are you diving into the world of Docker, or perhaps need a quick refresh on those essential commands? You’ve landed in the right place! Docker has revolutionized how we build, ship, and run applications, making development and deployment smoother than ever. But with great power comes a great many commands! π€―
This guide is your one-stop shop for mastering Docker. We’ll break down the most crucial commands, provide crystal-clear examples, and throw in some pro tips to make you a Docker wizard. Let’s get started! π³
1. Docker Essentials: The Commands You Can’t Live Without! β¨
These are the commands you’ll use day in and day out. Think of them as your Docker starter pack!
docker run
: Launching Your First Container πββοΈ
This is arguably the most important command. It creates and starts a new container from an image.
- Syntax:
docker run [OPTIONS] IMAGE [COMMAND] [ARG...]
- Common Options:
-d
: Detached mode (run in the background).-p HOST_PORT:CONTAINER_PORT
: Publish a container’s port(s) to the host.--name NAME
: Assign a name to your container.-it
: Interactive and pseudo-TTY (useful for entering a container’s shell).--rm
: Automatically remove the container when it exits.-v HOST_PATH:CONTAINER_PATH
: Mount a volume (for data persistence).
- Examples:
- Run an Nginx web server in the background, mapping host port 80 to container port 80:
docker run -d -p 80:80 --name my-nginx nginx:latest
- Run an Ubuntu container interactively to play around:
docker run -it --rm ubuntu:latest bash
- Run an Nginx web server in the background, mapping host port 80 to container port 80:
docker ps
: Listing Your Running Containers π
Need to see what’s currently active? docker ps
is your go-to.
- Syntax:
docker ps [OPTIONS]
- Common Options:
-a
or--all
: Show all containers (running and stopped).-s
or--size
: Display total file sizes.-f
or--filter "KEY=VALUE"
: Filter output based on conditions (e.g.,status=exited
).
- Examples:
- List all currently running containers:
docker ps
- List all containers (running and stopped):
docker ps -a
- List all currently running containers:
docker stop
/start
/restart
: Managing Container Lifecycle π
Control your containers’ state with these simple commands.
- Syntax:
docker stop [OPTIONS] CONTAINER [CONTAINER...]
(Same forstart
andrestart
) - Examples:
- Stop a container named
my-nginx
:docker stop my-nginx
- Start a previously stopped container:
docker start my-nginx
- Restart a running container:
docker restart my-nginx
- Stop a container named
docker rm
: Removing Containers ποΈ
When you’re done with a container, clean it up!
- Syntax:
docker rm [OPTIONS] CONTAINER [CONTAINER...]
- Common Options:
-f
or--force
: Force the removal of a running container (use with caution!).-v
or--volumes
: Remove anonymous volumes associated with the container.
- Examples:
- Remove a stopped container:
docker rm my-nginx
- Force-remove a running container (if
docker stop
doesn’t work or you’re impatient):docker rm -f my-nginx
- Remove a stopped container:
docker logs
: Peeking Inside Your Container’s Output π
Troubleshooting is a breeze when you can see what your container is doing.
- Syntax:
docker logs [OPTIONS] CONTAINER
- Common Options:
-f
or--follow
: Follow log output in real-time.-t
or--timestamps
: Show timestamps.--tail N
: Only show the last N lines of logs.
- Examples:
- View all logs for
my-nginx
:docker logs my-nginx
- Follow logs in real-time, showing the last 10 lines initially:
docker logs -f --tail 10 my-nginx
- View all logs for
2. Image Management: Building Blocks of Docker π§±
Images are the blueprints for your containers. Here’s how to manage them.
docker pull
: Downloading Images β¬οΈ
Get images from Docker Hub or a private registry.
- Syntax:
docker pull [OPTIONS] NAME[:TAG|@DIGEST]
- Examples:
- Download the latest Ubuntu image:
docker pull ubuntu:latest
- Download a specific version of Node.js:
docker pull node:16-alpine
- Download the latest Ubuntu image:
docker images
: Listing Local Images πΌοΈ
See what images you have stored on your machine.
- Syntax:
docker images [OPTIONS]
- Common Options:
-a
or--all
: Show all images (including intermediate image layers).-f
or--filter
: Filter images (e.g.,dangling=true
for unused images).
- Examples:
- List all downloaded images:
docker images
- List all downloaded images:
docker rmi
: Removing Images ποΈ
Free up disk space by deleting unused images.
- Syntax:
docker rmi [OPTIONS] IMAGE [IMAGE...]
- Common Options:
-f
or--force
: Force removal of an image, even if it’s used by a container.
- Examples:
- Remove the
ubuntu:latest
image:docker rmi ubuntu:latest
- Remove an image by its ID (useful for untagged images):
docker rmi a1b2c3d4e5f6 # Replace with actual image ID
- Remove the
docker build
: Creating Your Own Images π¨
This is where your applications truly shine in Docker! You create a Dockerfile
with instructions, and docker build
turns it into an image.
- Syntax:
docker build [OPTIONS] PATH | URL | -
- Common Options:
-t NAME:TAG
: Name and optionally tag the image.-f PATH/TO/Dockerfile
: Specify the path to the Dockerfile.
-
Example (assuming you have a Dockerfile in the current directory):
# Dockerfile example: # FROM node:16-alpine # WORKDIR /app # COPY package*.json ./ # RUN npm install # COPY . . # EXPOSE 3000 # CMD ["npm", "start"] docker build -t my-awesome-app:1.0 .
docker tag
: Giving Images Friendly Names π·οΈ
Assign a new tag to an existing image, often used before pushing to a registry.
- Syntax:
docker tag SOURCE_IMAGE[:TAG] TARGET_IMAGE[:TAG]
- Example:
- Tag
my-awesome-app:1.0
asyour-registry/my-app:production
:docker tag my-awesome-app:1.0 your-registry/my-app:production
- Tag
3. Container Deep Dive: Advanced Interactions πββοΈ
Beyond starting and stopping, these commands let you interact more deeply with your running containers.
docker exec
: Running Commands Inside a Container π§βπ»
A lifesaver for debugging or administrative tasks within a running container without needing to ssh
into it.
- Syntax:
docker exec [OPTIONS] CONTAINER COMMAND [ARG...]
- Common Options:
-it
: Interactive and pseudo-TTY (essential for shell access).
- Examples:
- Open a bash shell inside
my-nginx
container:docker exec -it my-nginx bash
- Check the Nginx version inside the container:
docker exec my-nginx nginx -v
- Open a bash shell inside
docker inspect
: Getting Detailed Information π§
Provides a wealth of low-level information about Docker objects (containers, images, volumes, networks).
- Syntax:
docker inspect [OPTIONS] NAME|ID [NAME|ID...]
- Common Options:
-f
or--format
: Format the output using Go template syntax (very powerful!).
- Examples:
- Get detailed info about
my-nginx
container:docker inspect my-nginx
- Just get the IP address of a container:
docker inspect -f '{{.NetworkSettings.IPAddress}}' my-nginx
- Get detailed info about
docker cp
: Copying Files To/From Containers πβ‘οΈ
Transfer files between your host machine and a running container.
- Syntax:
docker cp [OPTIONS] CONTAINER:PATH HOSTPATH
orHOSTPATH CONTAINER:PATH
- Examples:
- Copy a file from your host to
my-nginx
‘s/tmp
directory:docker cp my-local-file.txt my-nginx:/tmp/
- Copy a log file from
my-nginx
to your current host directory:docker cp my-nginx:/var/log/nginx/access.log .
- Copy a file from your host to
docker attach
: Connecting to a Container’s Standard I/O π
Attach your terminal’s standard input, output, and error to a running container. Useful for seeing immediate output.
- Syntax:
docker attach [OPTIONS] CONTAINER
- Example:
- Attach to
my-nginx
(you’ll see its output, usually Nginx access logs):docker attach my-nginx
- Pro Tip: To detach without stopping the container, press
Ctrl+P
thenCtrl+Q
.
- Attach to
4. Data Persistence & Sharing: Volumes πΎ
Containers are ephemeral by default. Volumes allow you to store data persistently and share it between containers or with the host.
docker volume create
: Making a Named Volume π
Create a managed volume that Docker maintains.
- Syntax:
docker volume create [OPTIONS] VOLUME
- Example:
docker volume create my-app-data
docker volume ls
: Listing Volumes π
See all the volumes managed by Docker on your system.
- Syntax:
docker volume ls [OPTIONS]
- Example:
docker volume ls
docker volume inspect
: Volume Details π
Get detailed information about a specific volume.
- Syntax:
docker volume inspect [OPTIONS] VOLUME [VOLUME...]
- Example:
docker volume inspect my-app-data
docker volume rm
: Deleting Volumes π₯
Clean up unused volumes. Be careful, this deletes the data!
- Syntax:
docker volume rm [OPTIONS] VOLUME [VOLUME...]
- Example:
docker volume rm my-app-data
Mounting Volumes with docker run -v
π
The -v
flag in docker run
is how you connect volumes to containers.
- Bind Mount:
HOST_PATH:CONTAINER_PATH
(mounts a directory from your host)docker run -d -p 80:80 -v /path/to/my/website:/usr/share/nginx/html --name my-static-site nginx:latest
- Named Volume:
VOLUME_NAME:CONTAINER_PATH
(uses a Docker-managed volume)docker run -d -p 3306:3306 -e MYSQL_ROOT_PASSWORD=secret -v my-db-data:/var/lib/mysql --name my-mysql-db mysql:latest
5. Networking: Connecting Your Containers π
Docker’s networking allows containers to communicate with each other and the outside world.
docker network create
: Custom Networks ποΈ
Create your own isolated networks for better organization and communication.
- Syntax:
docker network create [OPTIONS] NETWORK
- Common Options:
--driver BRIDGE_DRIVER
: Specify the network driver (default isbridge
).--subnet
,--gateway
: Define custom IP address ranges.
- Example:
docker network create my-app-network
docker network ls
: Listing Networks πΊοΈ
See all the networks on your system.
- Syntax:
docker network ls [OPTIONS]
- Example:
docker network ls
docker network inspect
: Network Details βΉοΈ
Get detailed information about a network, including connected containers.
- Syntax:
docker network inspect [OPTIONS] NETWORK [NETWORK...]
- Example:
docker network inspect my-app-network
Connecting Containers to a Network (docker run --network
) π€
Attach your container to a specific network. Containers on the same custom network can communicate by container name!
-
Example:
# Run a database container on our custom network docker run -d --network my-app-network --name my-db mongo:latest # Run an application container on the same network, connecting to 'my-db' docker run -d --network my-app-network --name my-web-app my-awesome-app:1.0
6. Orchestration Simplified: Docker Compose πΆ
For multi-container applications, docker-compose
is your best friend. It allows you to define and run a multi-container Docker application using a YAML file.
docker-compose.yml
Structure (Example) π
You’ll typically define your services, networks, and volumes in a docker-compose.yml
file.
# docker-compose.yml
version: '3.8' # Specify Compose file format version
services:
web:
build: . # Build from Dockerfile in current directory
ports:
- "80:80"
volumes:
- ./app:/usr/share/nginx/html # Mount local 'app' directory
networks:
- app-network
db:
image: postgres:13
environment:
POSTGRES_DB: mydb
POSTGRES_USER: user
POSTGRES_PASSWORD: password
volumes:
- db-data:/var/lib/postgresql/data # Named volume for persistence
networks:
- app-network
networks:
app-network:
driver: bridge # Define a custom network
volumes:
db-data: # Define a named volume
docker-compose up
: Bringing Your Application to Life β¬οΈ
Builds, creates, and starts all services defined in your docker-compose.yml
.
- Syntax:
docker-compose up [OPTIONS]
- Common Options:
-d
: Detached mode (run in the background).--build
: Rebuild images before starting containers.--force-recreate
: Recreate containers even if their configuration hasn’t changed.
- Examples:
- Start all services in detached mode:
docker-compose up -d
- Rebuild and start services:
docker-compose up -d --build
- Start all services in detached mode:
docker-compose down
: Stopping and Removing Services β¬οΈ
Stops and removes containers, networks, and volumes defined in your docker-compose.yml
.
- Syntax:
docker-compose down [OPTIONS]
- Common Options:
-v
: Remove named volumes declared in thevolumes
section of the Compose file.--rmi all
: Remove all images used by any service.
- Examples:
- Stop and remove services:
docker-compose down
- Stop, remove services, and their volumes:
docker-compose down -v
- Stop and remove services:
Other Useful Docker Compose Commands:
docker-compose build
: Builds or re-builds services.docker-compose ps
: Lists containers in the project.docker-compose logs [SERVICE_NAME]
: View logs for a specific service or all services.docker-compose exec [SERVICE_NAME] COMMAND
: Run a command inside a running service container.
7. Housekeeping & Cleanup: Keeping Docker Lean π§Ή
Docker can consume a lot of disk space. Regularly cleaning up unused objects is crucial.
docker system prune
: The Ultimate Cleaner! π₯
Removes all stopped containers, all dangling images, and all unused networks.
- Syntax:
docker system prune [OPTIONS]
- Common Options:
-a
or--all
: Remove all unused images (not just dangling ones), all stopped containers, all unused networks, and all build cache.--volumes
: Also remove all unused volumes.
- Examples:
- Basic cleanup:
docker system prune
- Aggressive cleanup (removes almost everything unused):
docker system prune -a --volumes
- Warning: This command is powerful and removes a lot. Be sure you don’t need the removed items!
- Basic cleanup:
8. Pro Tips & Best Practices for Docker! β
- Always use specific image tags:
nginx:1.21.3
is safer thannginx:latest
to ensure reproducible builds. - Leverage
docker-compose
: For anything more than a single container, it simplifies management immensely. - Clean up regularly: Use
docker system prune
to reclaim disk space. - Use volumes for persistence: Never store important data inside a container’s writable layer.
- Understand Docker networking: Custom networks are great for microservices and keeping services isolated but connected.
- Read the logs!
docker logs -f
is your best friend for debugging. - Don’t memorize everything: The beauty of a cheat sheet is that you don’t have to! Understand the concepts, and look up the specific commands as needed.
- Start small and experiment: The best way to learn Docker is by doing. Try running simple applications, building your own images, and experimenting with different commands.
Conclusion: Your Docker Journey Begins/Continues! π
You’ve now got a powerful arsenal of Docker commands at your fingertips! From launching simple containers to orchestrating complex multi-service applications with Docker Compose, you’re well-equipped.
Docker makes development, testing, and deployment consistent and efficient. Keep experimenting, keep building, and don’t be afraid to consult this cheat sheet whenever you need a quick reminder. Happy Dockering! π containers!