I'm practicing making a Golang web app that interacts with a PostgreSQL database, each running on their own container.
I'm running the containers with docker-compose up
But I seem to be failing on getting the postgres container properly set up.
For brevity, links to Dockerfile
s and other settings files are on this gist (let me know if you want it here instead).
version: '2'
services:
web_app:
build: dockerfiles/web_app
ports:
- "9000:9000"
volumes:
- .:/go/src/gitlab.com/repo/web_app
# links might be replaced by depends_on.
# links:
# - db
depends_on:
- db
# tty and stdin_open cause docker-compose to disconnect from docker-machine after 60sec.
# A fix is on the way.
# tty: true
# stdin_open: true
db:
build: dockerfiles/db
volumes:
- data:/var/lib/postgresql/data
volumes:
data: {}
docker-compose up
works fine. But when the application tries to open a database connection with:
var pgConf string = "user=web_app dbname=web_app sslmode=verify-full password=password"
db, err := sql.Open("postgres", pgConf)
I get the following error from docker compose:
Error creating new user: dial tcp [::1]:5432: getsockopt: connection refused
What can I do to make both containers talk to each other?
Thank you in advance.
When using the docker-compose v2, it's not needed to create links between services. Docker 1.9 and 1.10 allows you to connect to other containers on the same (custom) network through their name.
You should be able to connect using either the name of the service or the name of the container as a hostname. Given that the name of the container is generated by docker-compose, this is not really convenient to use, so for that reason, docker-compose also adds an alias with the service name to each container.
Take this very simple example. I've used an Nginx container for convenience, but the same should apply to your situation;
First start the project (assuming;
Then ping the "db" service from inside the
test_web_app_1
container:If you inspect the
test_db_1
container, you can see that docker-compose automatically added a "db" alias for thetest_db_1
container;Gives: (just the
NetworkSettings.Networks
part)