我有一个 CRUD 应用程序在我本地机器上的 Node 上运行。它在 Node 上运行,以 postgres 作为数据库,使用 knex.js 作为查询构建器等。
我已经创建了一个 docker 文件和一个 docker-compose 文件,并且容器启动了,但是 Node 容器无法访问 postgres 容器。我怀疑它与环境变量有关,但我不确定。这是我的 docker 文件:
FROM node:12
# Create app directory
WORKDIR /usr/src/app
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
COPY package*.json ./
RUN npm ci --only=production
# Bundle app source
COPY . .
ENV PORT=8080
EXPOSE 8080
CMD [ "npm", "start" ]
这是 docker-compose 文件:
version: '2'
services:
postgres:
image: postgres:alpine
environment:
POSTGRES_PASSWORD: password
POSTGRES_USER: app
POSTGRES_DB: db
app:
build: .
depends_on:
- "postgres"
links:
- "postgres"
environment:
DB_PASSWORD: 'password'
DB_USER: 'app'
DB_NAME: 'db'
DB_HOST: 'postgres'
PORT: 8080
ports:
- '8080:8080'
command: npm start
另外,这是根目录下的 knex.js
文件,它根据环境处理数据库连接:
// Update with your config settings.
module.exports = {
development: {
client: 'pg',
connection: 'postgres://localhost/db'
},
test: {
client: 'pg',
connection: 'postgres://localhost/test-db'
}
};
此外,当我检查 docker 中 Node 应用程序上的主机文件时,我没有看到任何提及 postgres 容器链接的内容。任何帮助将不胜感激,谢谢。
最佳答案
您的 Node 应用程序未连接的原因是因为它在您引用 localhost
时尝试连接到自身。您的数据库位于第二个非本地容器中,因此您需要通过服务名称引用它,服务名称为 postgres
。
因此假设您的应用程序以另一种方式处理身份验证,您的配置将是这样的:
// Update with your config settings.
module.exports = {
development: {
client: 'pg',
connection: 'postgres://postgres/db'
},
test: {
client: 'pg',
connection: 'postgres://postgres/test-db'
}
};
如果可以,您应该使用分配给 app
容器的环境变量。
关于node.js - 如何将 Node docker 容器与 postgres docker 容器连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58825501/