Ubuntu – PostgreSQL can’t bind to docker ip at boot (Cannot assign requested address)

dockerpostgresqlsystemdUbuntu

I am running PostgreSQL on the host machine. An application inside of a docker container should be able to communicate with the database. Since postgres is by default only listening for connections on localhost, I've changed the listen_addresses by adding the IP of the machine on the docker0 network interface, 172.17.0.1:

postgresql.conf:

[...]
listen_addresses = '127.0.0.1,172.17.0.1'
[...]

Changing the postgresql.conf and restarting the database works fine, it does what it should. However, when I'm rebooting the machine, I see that postgres isn't able to bind to the interface:

postgresql-10-main.log:

2019-12-09 23:03:10.202 UTC [935] LOG:  listening on IPv4 address "127.0.0.1", port 5432
2019-12-09 23:03:10.218 UTC [935] LOG:  could not bind IPv4 address "172.17.0.1": Cannot assign requested address
2019-12-09 23:03:10.218 UTC [935] HINT:  Is another postmaster already running on port 5432? If not, wait a few seconds and retry.
2019-12-09 23:03:10.218 UTC [935] WARNING:  could not create listen socket for "172.17.0.1"
[...]

Again, restarting postgres works fine – but I would like to not restart the database manually after a system reboot.

(Ubuntu 18.04, PostgreSQL installed via apt, Docker version 19.03.5, build 633a0ea838)

What I've tried

I was suspecting that the docker service or the network must start before postgres, so I tried adding a systemd file, but it doesn't work

/etc/systemd/system/postgresql.service.d/override.conf:

[Unit]
After=docker.service
After=network.target
Require=docker.service
Require=network.target

All the tutorials I can find suggest setting listen_addresses = '*', but since the server is directly connected to the internet I would like to avoid that.

Best Answer

In addition of overriding postgresql.service, override the postgresql@10-main.service as well.

For instance with systemctl edit postgresql@10-main.service then add:

[Unit]
After=docker.service 
Related Topic