Recreate pruned docker networks with docker-compose

So here is nice chain of docker errors and its solution.

1. Docker has reached its maximum of created networks and errors like this:

ERROR: could not find an available, non-overlapping IPv4 address pool among the defaults to assign to the network

The easiest (and most brute though) solution to this is to prune all networks, as suggested here on SO.

docker network prune

This will delete all networks that are not connected to currently active containers.
But this also means it will delete all networks of your not runnning dev projects.
(Which might be numerous as in my case.)

2. So next time you spin up another dev project the network will be missing, as it has been pruned and you will see this error:

Could not attach to network 726...: rpc error: code = NotFound desc = network 726... not found

Ok sure, the network is gone, but no problem let’s recreate it.
As described in this blog post.
We can simply add the —force-recreate option to docker-compose up and run it once then remove the option again to continue as usual.

docker-compose up --force-recreate

Also described here on SO.

Then we are back to normal in our dev docker environments.