« »
4/06/2017

docker-compose watch (a-k-a docker-compose reload) one-liner

Even if I often saw docker-compose misused...

... I do find it sometimes useful when I develop locally. But I can't bear the cmd+tab + ctrl+c + up + enter each time I want to reload my containers because some configuration file changed. I'm not the only one, an issue exists on docker-compose project since 2014 (Watch code and automatically rebuild when something changes).

So here is a one-liner that works and restart docker-compose each time a *.yml, *.toml or *.conf file change:

watchexec --restart --exts "yml,toml,conf" --watch . "docker-compose up"

I used watchexec (rust) but you could definitely use something else like nodemon (nodejs).

And if you wish to restart docker-compose each time files from a specific folder are updated (e.g. api/), --filter is what you are looking for:

watchexec --restart --filter "$(pwd)/api/*" --watch . "docker-compose up"

For extra sweetness — because who wants to remember this one-liner forever? — I put the function below in my ~/.zshrc

function docker-compose-watch() {
  local args;
  if [[ $1 == "help" ]] || [[ $1 = "--help" ]]; then
    watchexec --help | grep -A 3 "OPTIONS:";
    return;
  else
    args='--filter "*/docker-compose.yml"' && [[ $1 ]] && args=$@;
  fi
  eval watchexec --restart $args -w $(pwd) "docker-compose up"
}

alias docker-compose-reload=docker-compose-watch;

Usage:

docker-compose-watch --help
OPTIONS:
    -e, --exts         Comma-separated list of file extensions to watch (js,css,html)
    -f, --filter ...      Ignore all modifications except those matching the pattern
    -i, --ignore ...      Ignore modifications to paths matching the pattern
docker-compose-watch -e '*.js' -i './api'
Starting api_worker_1
Starting api_postgrest_1
Attaching to api_worker_1, api_postgrest_1
[... updating a file ...]
Gracefully stopping... (press Ctrl+C again to force)
Stopping api_postgrest_1 ... done
Stopping api_worker_1 ... done
Starting api_worker_1
Starting api_postgrest_1

Note: I definitely prefer to restart docker-compose up after each file change (with soft shutdown) than have to first remember to run docker-compose up and then run watchexec ... "docker-compose restart" and finally ctrl+c + docker-compose down.

« »
 
 
Made with on a hot august night from an airplane the 19th of March 2017.