The docker-compose-alias pattern
To manage a Docker Compose stack, you must either run docker-compose
from the directory containing the docker-compose.yml
file, or specify its path with the --file
option.
This can get tiring if you have to manage multiple stacks or if you’re using Compose files with custom names such as docker-compose.prod.yml
.
In this case, a very simple yet effective trick is to use shell aliases.
Let’s consider an application named iris
and its associated docker-compose.prod.yml
file in the /iris
directory.
By defining the following alias in our shell configuration:
alias iris="docker-compose -f /iris/docker-compose.prod.yml"
we can manage our stack with the iris
command:
iris ps
iris logs
iris [...]
# equivalent to
docker-compose -f /iris/docker-compose.prod.yml [...]
Running as another user
If we need to run Compose as another user, for example iris
, we can use the following function:
# bash
iris() {
cmd="docker-compose -f /iris/docker-compose.prod.yml $*"
su --login --command "${cmd}" iris
}
# fish
function iris
set cmd "docker-compose -f /iris/docker-compose.prod.yml $argv"
su --login --command "$cmd" iris
end
Running on a remote host
To run Compose on a remote host, we can use the following function:
# bash
iris() {
cmd="docker-compose -f /iris/docker-compose.prod.yml $*"
ssh user@remote-host "${cmd}"
}
# fish
function iris
set cmd "docker-compose -f /iris/docker-compose.prod.yml $argv"
ssh user@remote-host "$cmd"
end