[英]Failed to connect to postgre database inside docker container
docker-compose.yaml docker-compose.yaml
version: '3.9'
services:
web:
env_file: .env
build: .
command: sh -c "alembic upgrade head && uvicorn main:app --host 0.0.0.0 --port 8000"
volumes:
- .:/app
ports:
- 8000:8000
depends_on:
- db
- redis
db:
image: postgres:11
volumes:
- postgres_data:/var/lib/postgresql/data
environment:
- POSTGRES_USER=${DB_USER}
- POSTGRES_PASSWORD=${DB_PASS}
- POSTGRES_DB=${DB_NAME}
redis:
image: redis:6-alpine
volumes:
postgres_data:
.env .env
DB_USER='wplay'
DB_PASS='wplay'
DB_HOST=db
DB_NAME='wplay'
DB_PORT=5432
When I running docker container当我运行 docker 容器时
web_1 | could not connect to server: Cannot assign requested address
web_1 | Is the server running on host "localhost" (::1) and accepting
web_1 | TCP/IP connections on port 5432?
I try to change.env DB_HOST='localhost'
and add我尝试 change.env
DB_HOST='localhost'
并添加
ports:
- '5432:5432'
to yaml db
configuration, but nothing到 yaml
db
配置,但没有
upd更新
logs日志
db_1 |
db_1 | PostgreSQL Database directory appears to contain a database; Skipping initialization
db_1 |
db_1 | 2023-01-04 12:44:55.386 UTC [1] LOG: listening on IPv4 address "0.0.0.0", port 5432
db_1 | 2023-01-04 12:44:55.386 UTC [1] LOG: listening on IPv6 address "::", port 5432
Connection to DB连接到数据库
db.py数据库文件
import os
from decouple import config
import databases
import sqlalchemy
DEFAULT_DATABASE_URL = f"postgresql://{config('DB_USER')}:{config('DB_PASS')}" \
f"@{config('DB_HOST')}:5432/{config('DB_NAME')}"
DATABASE_URL = (os.getenv('DATABASE_URL', DEFAULT_DATABASE_URL))
database = databases.Database(DATABASE_URL)
metadata = sqlalchemy.MetaData()
engine = sqlalchemy.create_engine(DATABASE_URL)
metadata.create_all(engine)
You are spinning up two individual containers - a "web" and a "db" but trying to connect to the other by localhost
.您正在启动两个单独的容器 - 一个“web”和一个“db”,但试图通过
localhost
连接到另一个。 localhost
will only resolve to within it's own container. localhost
只会在它自己的容器内解析。
with Docker Run用 Docker 运行
Use -.network="host"
in your docker run
command, then localhost
and 127.0.0.1
in your docker container will point to your docker host.在
docker run
命令中使用-.network="host"
,然后 docker 容器中的localhost
和127.0.0.1
将指向您的 docker 主机。
With Docker Compose与 Docker 撰写
Each container can look up the hostname web or db and get back the appropriate container's IP address.每个容器都可以查找主机名 web 或 db 并取回相应容器的 IP 地址。 For example,
web
's application code could connect to the URL postgres://db:5432
and start using the Postgres database.例如,
web
的应用程序代码可以连接到 URL postgres://db:5432
并开始使用 Postgres 数据库。
Within the web
container, your connection string to db would look like postgres://db:5432
在
web
容器中,您到 db 的连接字符串看起来像postgres://db:5432
See docker documentation or docker compose documentation请参阅docker 文档或docker 撰写文档
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.