Docker Cheat Sheet
Introduction
Docker is a platform that enables developers to automate the deployment of applications inside lightweight, portable containers. Containers are isolated environments that include everything needed to run an application, ensuring consistency across different environments. This cheat sheet provides a detailed guide to essential Docker commands and concepts.
Docker Basics
1. Installation
Linux:
sudo apt-get update sudo apt-get install docker-ce docker-ce-cli containerd.io
Windows/Mac: Download and install Docker Desktop from the official website.
2. Hello World
Run a simple container:
docker run hello-world
3. Containers
List running containers:
docker ps -a
List all containers (including stopped ones):
Stop a running container:
docker stop <container_id>
Remove a container:
docker rm <container_id>
4. Images
List local images:
docker images
Remove an image:
docker rmi <image_id>
5. Dockerfile
Create a Dockerfile:
FROM ubuntu
RUN apt-get update && apt-get install -y python
CMD ["python", "--version"]
Build an image:
docker build -t my-python-app .
Run a container from the built image:
docker run my-python-app
Advanced Docker Commands
6. Networking
List networks:
docker network ls
Create a custom network:
docker network create my-network
7. Volumes
List volumes:
docker volume ls
Create a named volume:
docker volume create my-volume
8. Compose
Create a docker-compose.yml
file:
version: '3'
services:
web:
image: nginx
ports:
- "80:80"
Run services defined in the docker-compose.yml
file:
docker-compose up
9. Environment Variables
Set environment variables while running a container:
docker run -e MY_VARIABLE=value my-image
10. Docker Swarm
Initialize a Swarm:
docker swarm init
Deploy a stack:
docker stack deploy -c docker-compose.yml my-stack
Best Practices
11. Tags and Versioning
Use specific image tags for versioning:
docker pull nginx:1.18
12. Cleanup
Remove all stopped containers:
docker container prune
Remove all unused images:
docker image prune -a
13. Security
Avoid running containers as root:
docker run --user nonrootuser my-image
Limit container resources:
docker run --memory=512m --cpu-shares=2 my-image
Troubleshooting
14. Logs
View container logs:
docker logs <container_id>
15. Exec
Execute a command in a running container:
docker exec -it <container_id> /bin/bash
16. Inspect
Get detailed information about a container or image:
docker inspect <container_or_image_id>
Conclusion
Docker simplifies the process of packaging and deploying applications, providing a consistent environment across different systems. This cheat sheet covers essential Docker commands, concepts, and best practices to help you effectively manage containers in your development and deployment workflows. Explore Dockers documentation for more in-depth information and advanced use cases.