我无法从Fedora主机上的应用程序容器连接到db容器。我已经验证了能够通过psql命令行界面使用相同的凭据连接到数据库。在我的应用程序中使用相同的信息无效。
这是我的docker compose文件
version: '3.3'
services:
postgrestest:
build: ./vrs
command: python3 app.py
volumes:
- ./vrs/:/appuser/
ports:
- 5000:5000
env_file:
- ./.env.dev
depends_on:
- db
db:
image: postgres:12-alpine
volumes:
- postgres_data:/var/lib/postgresql/data/
environment:
- POSTGRES_USER={{user}}
- POSTGRES_PASSWORD={{password}}
- POSTGRES_DB=sharepointvrs
volumes:
postgres_data:
这是用于从应用程序容器内部连接到容器的代码:
dbconfig = environment["database"]
try:
connection = psycopg2.connect(
dbname=dbconfig["dbname"], #sharepointvrs
user=dbconfig["user"],
password=dbconfig["password"],
host=dbconfig["host"], # tried 0.0.0.0, localhost, and IP address obtained from docker inspect
port=dbconfig["port"] # 5432
)
connection.autocommit = True
except:
print("Database initialization failed.")
我尝试使用本地主机和运行docker inspect获得的IP:
答案 0 :(得分:1)
# tried 0.0.0.0, localhost, and IP address obtained from docker inspect
在应用程序的配置中,将数据库主机设置为'db'
作为DNS别名存在,根据您在撰写文件中设置的服务名称,在其他容器中可用:
services:
db:
# ...
答案 1 :(得分:1)