简体   繁体   English

如何公开一个Docker容器访问主机数据库?

[英]How to expose a docker container to access host database?

I'm currently trying to figure out how to configure my docker-compose.yml to allow a web-server (django) to communicate with a PostgreSQL database running on the host machine. 我目前正在尝试弄清楚如何配置docker-compose.yml以允许Web服务器(django)与主机上运行的PostgreSQL数据库进行通信。

The app is perfectly working outside of a container. 该应用程序可以在容器外部完美运行。

And now I want to create a container for better management and deployment capabilities. 现在,我想创建一个容器,以提供更好的管理和部署功能。

I've tried this, 我已经试过了
docker-compose.yml : docker-compose.yml

version: '3'

services:
  web:
    image: myimage
    volumes:
      - .:/appdir
    environment:
      - DB_NAME=test
      - DB_USER=test
      - DB_PASSWORD=test
      - DB_HOST=localhost
    command: python manage.py runserver 0.0.0.0:8000
    ports:
      - "8000:8000"
    networks:
      - mynet
networks:
  mynet:

Dockerfile : Dockerfile的

FROM python:3

ENV PYTHONUNBUFFERED=1 \
    DJANGO_SETTINGS_MODULE=app.settings \
    DEBUG=True \
    SECRET_KEY=akey

WORKDIR /appdir

COPY . /appdir

EXPOSE 8000

RUN pip install -r requirements.txt

But when I do so, I get the following error : 但是当我这样做时,出现以下错误:

web_1  | django.db.utils.OperationalError: could not connect to server: Connection refused
web_1  |        Is the server running on host "localhost" (127.0.0.1) and accepting
web_1  |        TCP/IP connections on port 5432?

Thanks 谢谢

localhost is relative - inside the docker container - localhost (aka 127.0.0.1) refers to the container itself. localhost是相对的-在docker容器内部-本地主机(aka 127.0.0.1)是指容器本身。 if you want to connect to your host- give the container your host real ip as the DB_HOST . 如果要连接到主机,请为容器提供您主机的真实IP作为DB_HOST

there are many ways to find your host ip, for instance: run in your terminal hostname -I | awk '{print $1}' 查找主机IP的方法有很多,例如:在终端hostname -I | awk '{print $1}'运行。 hostname -I | awk '{print $1}'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM