[英]Authentication error when connecting to Postgres in a Docker container
[英]Error when connecting to postgres from a Python container
我正在嘗試將兩個通信容器設置為不同的服務
這是我的Dockerfile
FROM python:3.8.8-slim-buster
RUN mkdir /project
WORKDIR /project
COPY . /project/
RUN apt-get update && \
apt-get install --no-install-recommends -y \
build-essential \
bash
RUN pip install --upgrade --no-use-pep517 \
pip \
setuptools \
wheel \
jupyterlab \
ipython-sql \
psycopg2-binary
EXPOSE 8888
和我docker-compose.yml
version: '3'
services:
db:
image: postgres:12.1-alpine
environment:
- POSTGRES_DB=ps_db
- POSTGRES_USER=ps_user
- POSTGRES_PASSWORD=ps_pass
ports:
- "5432:5432"
web:
build:
context: .
command:
jupyter notebook --ip=0.0.0.0 --port=8888 --no-browser --allow-root
volumes:
- .:/project
ports:
- "8888:8888"
depends_on:
- db
雖然我很確定我的設置很好,但每當我運行
import psycopg2
conn = psycopg2.connect(database="ps_db", user="ps_user", password="ps_pass", host="0.0.0.0", port=5432)
我收到這個錯誤
OperationalError: could not connect to server: Connection refused
Is the server running on host "0.0.0.0" and accepting
TCP/IP connections on port 5432?
您需要將 0.0.0.0 IP 設置為 'db',因為 postgres 運行在另一個名為 'db' 的容器中,這是您的服務的名稱。 所以你的 conn 看起來像這樣:
conn = psycopg2.connect(database="ps_db", user="ps_user", password="ps_pass", host="db", port=5432)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.