Tips & Tricks
Simplify docker compose files
When working with a larger app-stack, that uses multiple different services, a lot of times different settings get reused. To simplify we can use yaml anchors and aliases.
Imagine we have the following servies:
version: "3.4"
services:
app1:
image: app1
networks:
- net1
- net2
restart: unless-stopped
app2:
image: app3
networks:
- net1
- net2
restart: unless-stopped
app3:
image: app3
networks:
- net1
- net2
restart: unless-stopped
We can see, that the restart policy and the networks are repeated for every single service. We could simplify like this:
version: "3.4"
x-app_default: &app_default
networks:
- net1
- net2
restart: unless-stopped
services:
app1:
<<: *app_default
image: app1
app2:
<<: *app_default
image: app3
app3:
<<: *app_default
image: app3
Starting from compose version 3.4 docker ignores top-level keys that start with x-
. In the example above, wherever we write <<: *app_default
, everything given after x-app_default: &app_default
gets inserted.
If a key-value pair is specified in app_default
and also in one of the services, the app_default
values get overwritten entirely.
For more information see here.
Docker aliases
The following are examples for aliases, that can be used to start or stop apps.
alias dcup='docker compose up -d'
alias dcdn='docker compose down'
alias dcl='docker compose logs -f'
To use these, simply add them to your ~/.bashrc
and log out and back in or alternatively use source ~/.bashrc
.