How to connect a Docker web application container to a PostgreSQL Docker container?

I am creating a Golang web application that interacts with a PostgreSQL database, each of which runs in its own container.

I run containers with docker-compose up

But I seem to be unable to properly configure the postgres container.

For brevity, links to Dockerfileand other settings files at this value (let me know if you want it here).

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 upworks great. But when the application tries to open a database connection:

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?

Thanks in advance.

+4
1

docker-compose v2 . Docker 1.9 1.10 () .

, , . , docker-compose, , docker-compose .

. Nginx , ;

version: '2'
services:
  web_app:
    image: nginx
  db:
    image: nginx

(;

$ docker-compose --project-name=test up -d
Creating network "test_default" with the default driver
Creating test_db_1
Creating test_web_app_1

ping "db" test_web_app_1:

$ docker exec -it test_web_app_1 ping -c 2 db
PING db (172.18.0.2): 56 data bytes
64 bytes from 172.18.0.2: icmp_seq=0 ttl=64 time=0.108 ms
64 bytes from 172.18.0.2: icmp_seq=1 ttl=64 time=0.243 ms
--- db ping statistics ---
2 packets transmitted, 2 packets received, 0% packet loss
round-trip min/avg/max/stddev = 0.108/0.175/0.243/0.068 ms

test_db_1, , docker-compose "db" test_db_1;

$ docker inspect test_db_1

: ( NetworkSettings.Networks)

"Networks": {
    "test_default": {
        "IPAMConfig": null,
        "Links": null,
        "Aliases": [
            "db",
            "002b1875e61f"
        ],
        "NetworkID": "0f9e2cddeca79e5a46c08294ed61dee273828607f99014f6410bda887626be70",
        "EndpointID": "a941ab95586a8fdafc5075f9c5c44d745f974e5790ef6048b9e90115a22fb31f",
        "Gateway": "172.18.0.1",
        "IPAddress": "172.18.0.2",
        "IPPrefixLen": 16,
        "IPv6Gateway": "",
        "GlobalIPv6Address": "",
        "GlobalIPv6PrefixLen": 0,
        "MacAddress": "02:42:ac:12:00:02"
    }
}
+7

All Articles