Skip to content

Instantly share code, notes, and snippets.

@averagehuman
Last active April 3, 2019 22:36
Show Gist options
  • Save averagehuman/fcabcd0847a36ced38a9 to your computer and use it in GitHub Desktop.
Save averagehuman/fcabcd0847a36ced38a9 to your computer and use it in GitHub Desktop.
Run postgres on docker host, connect from docker containers
#!/bin/bash
################################################################################
# Rather than run postgres in its own container, we want to run it on
# the (Ubuntu) host and allow:
#
# + peer connections on the host
# + local md5 connections from any docker container
#
# THIS IS COPY/PASTED FROM COMMAND LINE INPUT AND IS UNTESTED AS A SINGLE SCRIPT
################################################################################
# Determine the docker bridge IP address (assumed to be docker0)
bridge_ip=$(ifconfig docker0 | grep "inet addr:" | awk '{print $2}' | sed "s/.*://")
# subnet for container interfaces
docker_subnet="172.17.1.0/24"
# update postgresql.conf to listen only on the bridge interface
sed -i.orig "s/^[#]\?listen_addresses .*/listen_addresses = '${bridge_ip}'/g" /etc/postgresql/9.3/main/postgresql.conf
# update pg_hba.conf to allow connections from the subnet
echo "host all all ${docker_subnet} md5" >> /etc/postgresql/9.3/main/pg_hba.conf
# update ufw firewall rules (postgres assumed to be runing on port 5432)
ufw allow in from ${docker_subnet} to ${bridge_ip} port 5432
echo "Restart of postgres and ufw services is now required"
@nielsonsantana
Copy link

The current subnet used by docker aren't 172.17.0.1/16?
https://docs.docker.com/engine/userguide/networking/dockernetworks/

@dgolant
Copy link

dgolant commented Dec 3, 2017

That last line about UFW just fixed an issue I was dealing with for 2 days. Thank you so much. 🙏

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment