Docker Cheat Sheet
A little cheat sheet for Docker, when you just remember a specific command.
Glossary
- Layer
- Image
- Container
- Registry
- Docker Engine / Daemon
- Docker Compose
Useful commands for creating and running containers
Download an image
docker pull image_name
Start and Stop a container
docker [start|stop] container_id|container_name
Create and start a continuer
docker run -it --name container_name image_name command
Create and start a container, and destroy after execution
docker run --rm -it image_name command
Map filesystem, port and environment variables
- Container
80🠦Host 8080 - Host
/home/user/container_data🠦 Container/data - Variable:
HTTP_PROXY🠦http://proxy.tld:port/
docker run -it --rm -p 80:8080 -v /home/user/container_data:/data -e HTTP_PROXY="http://proxy.tld:port/" image_name command
Create and start a container as daemon (service)
docker -d --name container_name image_name command
Useful commands for cleaning up
Force stop (kill) a container
docker kill container_id|container_name
KIll all running containers
docker kill $(docker ps -q)
Remove stopped a container
docker rm container_id|container_name
Force remove a running container
docker rm --force container_id|container_name
Remover all stopped containers
docker rm $(docker ps -q)
Interact with containers
Run a command inside a running container
docker exec -it container_id|container_name command
Show logs from a running container
docker logs -ft container_id|container_name
docker attach
Create an image from container
docker commit -m "commit message" -a "author" container_id|container_name username/image_name:tag
Docker File
Dockerfile
Example of a dockerfile to run busybox
FROM scratch
ADD busybox.tar.xz /
CMD ["sh"]
Explanation
FROM scratch: usescratchas base image.ADD busybox.tar.xz /: Copy busybox from working directory (same asDockerfile) and extract it to/.CMD ["sh"]: tell docker startsh.
Build container
docker build .
Replace . with the path to Dockerfile, to use a Dockerfile in another directory.
Docker Compose
Example of a docker-compose.yml to run a Wordpress blog.
version: '3.3'
services:
db:
image: mysql:5.7
volumes:
- db_data:/var/lib/mysql
restart: always
environment:
MYSQL_ROOT_PASSWORD: somewordpress
MYSQL_DATABASE: wordpress
MYSQL_USER: wordpress
MYSQL_PASSWORD: wordpress
wordpress:
depends_on:
- db
image: wordpress:latest
ports:
- "8000:80"
restart: always
environment:
WORDPRESS_DB_HOST: db:3306
WORDPRESS_DB_USER: wordpress
WORDPRESS_DB_PASSWORD: wordpress
volumes:
db_data:
Explanation
version: specify which version ofdocker-composeto use.services: list of images to useimage: specify which image to usedepends_on: tell docker other image dependenciesvolumes: refer persistent data storage defined belowports: what ports to expose, otherwise you will not be able to access the applicationrestart: always: tells docker to restart image, each restartenvironment: define environment variables
volumes: list of persistent data storage