【问题标题】:Accessing container-side Postgres database via container-side Node.js web app通过容器端 Node.js Web 应用访问容器端 Postgres 数据库
【发布时间】:2019-09-03 14:20:17
【问题描述】:

我有一个 Node.js 应用程序的 Dockerfile,总体看起来像这样:

FROM ubuntu
RUN rm /bin/sh && ln -s /bin/bash /bin/sh

WORKDIR /app
COPY . /app

ENV DEBIAN_FRONTEND noninteractive
RUN apt-get update
RUN apt-get install -y -q --no-install-recommends \
        apt-transport-https \
        build-essential \
        ca-certificates \
        curl \
        git \
        libssl-dev \
        wget \
        postgresql-10 postgresql-client-10 postgresql-contrib-10

USER postgres
RUN    /etc/init.d/postgresql start &&\
    psql --command "CREATE USER warbler WITH SUPERUSER;" &&\
    createdb -O warbler warbler_store

# ... node setup stuff ...
# ...
# ...

RUN psql -U warbler -d warbler_store -f db_v1.sql

CMD ["node", "index.js"]

虽然我收到以下错误消息:

psql: could not connect to server: No such file or directory
    Is the server running locally and accepting
    connections on Unix domain socket "/var/run/postgresql/.s.PGSQL.5432"?

我在网上浏览了一下,我发现的大多数解决方案似乎都说 docker 正在尝试连接到 host postgres 实例,以及其他与主要目的是运行 PostgreSQL 的 docker 容器。这准确吗?如果准确,是否仍然可以运行主应用程序可以访问的容器端 PostgreSQL 实例?

【问题讨论】:

    标签: node.js postgresql docker


    【解决方案1】:

    显然,将数据库与 Web 应用程序放在同一个 Docker 容器中并不是一个好习惯。我通过在另一个容器中使用postgresql:10 图像并让Web 应用程序通过docker-compose 与其通信来更改我的容器结构。 docker-compose 允许定义服务,Docker 的内部 DNS 将允许它们相互通信

    这是docker-compose.yaml 的样子:

    version: '3'
    services:
        web:
            build: .
            ports:
            - "3000:3000"
            volumes:
            - .:/app
            links:
            - db
    
        db:
            image: postgres:10
            environment:
            - POSTGRES_USER=warbler
            - POSTGRES_DB=warbler_store
            volumes:
            - ./db_v1.sql:/docker-entrypoint-initdb.d/db_v1.sql
            - dbdata:/var/lib/postgresql/data
    
    volumes:
        dbdata:
    

    在这种情况下,在 web 的 Dockerfile 中,我设置了必要的环境变量,以便 Node 连接到运行在 postgresql://db:5432/warbler_store 的数据库。 db 通过 DNS 解析到运行 db 服务的容器的 IP 地址,也就是 postgres 镜像容器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-04
      • 1970-01-01
      • 2016-10-09
      • 2021-02-18
      • 1970-01-01
      • 1970-01-01
      • 2018-04-21
      • 1970-01-01
      相关资源
      最近更新 更多