Django + Docker:连接到“localhost”(127.0.0.1)服务器,端口 5432 失败

Ale*_*lex 12 django postgresql nginx docker

我正在尝试在 docker 中运行我的 Django 应用程序(Nginx、Gunicorn)。

但对于请求http://167.99.137.32/admin/我有错误:(完整日志https://pastebin.com/0f8CqCQM

onnection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused
    Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (::1), port 5432 failed: Address not available
    Is the server running on that host and accepting TCP/IP connections?
Run Code Online (Sandbox Code Playgroud)

我正在尝试Can't run the server on Django (connection returned)的答案,但没有解决我的问题

设置.py

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'lk_potok_2',
        'USER': 'postgres',
        'PASSWORD': 'post222',
        'HOST': 'localhost',
        'PORT': 5432,
    },
Run Code Online (Sandbox Code Playgroud)

docker-compose.yml

version: '3.9'

services:
  django:
    build: . # path to Dockerfile
    command: sh -c "gunicorn --bind 0.0.0.0:8000 potok.wsgi:application"
    volumes:
      - .:/project
      - static:/project/static
    expose:
      - 8000
    environment:
      - DATABASE_URL=postgres://postgres:post222@localhost:5432/lk_potok_2"
      - DEBUG=1

  db:
    image: postgres:13-alpine
    volumes:
      - pg_data:/var/lib/postgresql/data/
    expose:
      - 5432
    environment:
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=post222
      - POSTGRES_DB=lk_potok_2

  nginx:
    image: nginx:1.19.8-alpine
    depends_on:
      - django
    ports:
      - "80:80"
    volumes:
      - static:/var/www/html/static
      - ./nginx-conf.d/:/etc/nginx/conf.d

volumes:
    pg_data:
    static:
Run Code Online (Sandbox Code Playgroud)

nginx-conf.nginx

upstream app {
    server django:8000;
}

server {
    listen 80;
    server_name 167.99.137.32;

    location / {
        proxy_pass http://django:8000;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $host;
        proxy_redirect off;
    }

    location /static/ {
        alias /var/www/html/static/;
    }
}
Run Code Online (Sandbox Code Playgroud)

我正在尝试sudo systemctl start postgresqlsudo systemctl enable postgresql(同样的错误)

Dru*_*ann 21

postgres 数据库不再在 运行localhost。在你的情况下(因为你命名了容器db)它是db

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'lk_potok_2',
        'USER': 'postgres',
        'PASSWORD': 'post222',
        'HOST': 'db',
        'PORT': 5432,
    },
Run Code Online (Sandbox Code Playgroud)

我真的不明白为什么你要在这里添加这个:

environment:
      - DATABASE_URL=postgres://postgres:post222@localhost:5432/lk_potok_2"
Run Code Online (Sandbox Code Playgroud)

因为你不在你的settings.py. 但在这里它也必须db代替localhost

- 编辑 -

为什么可以识别其他容器的解释可以在这里docker找到。