如何将Docker Web应用容器连接到Docker PostgreSQL容器?

huangapple go评论108阅读模式
英文:

How to connect Docker web app container to Docker PostgreSQL container?

问题

我正在练习制作一个与 PostgreSQL 数据库交互的 Golang Web 应用程序,它们分别在自己的容器中运行。

我使用 docker-compose up 命令来运行容器。

但是我似乎无法正确设置 postgres 容器。

为了简洁起见,Dockerfile 和其他设置文件的链接在这个 gist上(如果你想要在这里看到它,请告诉我)。

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 命令正常工作。但是当应用程序尝试使用以下代码打开数据库连接时:

var pgConf string = "user=web_app dbname=web_app sslmode=verify-full password=password"

db, err := sql.Open("postgres", pgConf)

我从 docker compose 得到以下错误:

Error creating new user: dial tcp [::1]:5432: getsockopt: connection refused

我该如何使两个容器彼此通信?

提前谢谢你。

英文:

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 Dockerfiles 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.

答案1

得分: 8

在使用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

然后从test_web_app_1容器内部ping一下db服务:

$ 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自动为test_db_1容器添加了一个名为"db"的别名;

$ 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"
    }
}
英文:

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;

<!-- language: lang-YAML -->

version: &#39;2&#39;
services:
  web_app:
    image: nginx
  db:
    image: nginx

First start the project (assuming;

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

Then ping the "db" service from inside the test_web_app_1 container:

$ 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

If you inspect the test_db_1 container, you can see that docker-compose automatically added a "db" alias for the test_db_1 container;

$ docker inspect test_db_1

Gives: (just the NetworkSettings.Networkspart)

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

huangapple
  • 本文由 发表于 2016年3月27日 11:35:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/36243559.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定