Docker Compose Cheatsheet
Published: 2022-09-09This page lists some common Docker Compose configurations and commands. Docker Compose is very useful for self-hosting because it is relatively simple to use and requires all the features that you need for self-hosting. One the one hand, Docker Compose setups are specified via declarative files meaning that re-installing a server should be possible within a few hours if have your backups. One the other hand, Docker Compose is much simpler than container orchestration tools such as Kubernetes. If you have never used the tool before, then take a look at the simple tutorial.
First of all, the most common elements of docker-compose.yml
are:
version: '3'
services:
caddy:
image: 'caddy:2.7.5-alpine'
container_name: 'caddy'
ports:
- '80:80'
- '443:443'
volumes:
- '/data/caddy:/data:rw'
- './index.html:/public/index.html:ro'
- './Caddyfile:/Caddyfile:ro'
user: '2000:2000'
logging:
driver: 'json-file'
options:
max-size: '10m'
max-file: '10'
environment:
MY_USERNAME: 'username'
env_file:
- 'MY_PASSWORD.env'
command: 'caddy run --config /Caddyfile --adapter caddyfile'
restart: 'unless-stopped'
Notes:
Using quotes generously can avoid hard-to-find bugs.
The
volumes
specify a mapping<from>:<to>:<permissions>
. Adding therw
(read-write) orro
(read-only) permissions is optional, but generally a good idea since being explicit is good.Instead of
ports
, it is common to usenetwork_mode: 'host'
when more flexibility is needed.In the example, the
image
version is explicitly set to2.5.1-alpine
to avoid random errors for hosted services caused by random image updates.restart
is set tounless-stopped
since setting it toalways
makes it hard to stop containers.By default, the default user within a container is root (UID: 0). To reduce the risk that an attacker breaks out of the container and obtains root access to the server, set the user explicitly to an unique user id (UID) and group id (GUID) other than root (UID: 0). This also reduces the chance of attackers reading secrets if you ensure that secret files can only be read by the root user.
For more about secrets, see Securing Docker Compose Secrets.
The next docker compose
calls, assume that you are in the same directory as your docker-compose.yml
file.
To start a configuration and attach standard out to the logs, use:
$ docker compose up
Note that hitting CTRL + C
will stop the services again. So, to start a configuration in the background (without seeing the logs), --detach
it:
$ docker compose up -d
and take it down again via:
$ docker compose down
To test a Docker image manually, use:
$ docker run -it --rm caddy:2.5.1-alpine sh
where sh
starts the default shell. sh
is available in most Docker images.
Make sure to specify container_name: caddy
in docker-compose.yml
. This allows for stepping into the running container with:
$ docker exec -it caddy sh
and viewing the logs with:
$ docker logs caddy