如何从docker容器连接到localhost postgres数据库?

我configuration我的项目到docker。 我有数据库已经在非docker期间使用,现在我想连接我的docker-compose数据库服务。 但是,当我写docker-compose up – 现有的数据库没有使用 – 新创build一个(我怀疑,docker容器根本没有看到数据库)。 如果我做废话,请让我知道。 也许我应该迁移我的服务器数据库到容器。

这是我的docker-compose.yml:

 services: db: restart: always image: postgres:latest environment: - POSTGRES_DB=mydb - POSTGRES_PASSWORD=p@ssw0rd - POSTGRES_USER=root ports: - "5432:5432" volumes: # We'll mount the 'postgres-data' volume into the location Postgres stores it's data: - postgres-data:/var/lib/postgresql/data web: build: . command: bash -c "python manage.py collectstatic --noinput && ./manage.py migrate && ./run_gunicorn.sh" volumes: - .:/code - /static:/static ports: - 443:443 depends_on: - db nginx: restart: always image: nginx:latest ports: - 80:80 volumes: - ./misc/nginx.conf:/etc/nginx/conf.d/default.conf - /static:/static depends_on: - web 

我认为,canonic方法是让数据库引擎在容器中运行,同时将数据存储在永久性存储上(将卷映射到硬盘上)。 所以我会使用Docker中的Postgres作为ServerDB,正如你所build议的那样。

如果您只希望您的应用程序连接到外部数据库,请将其声明为外部主机:

 version: '2' services: web: build: . command: bash -c "python manage.py collectstatic --noinput && ./manage.py migrate && ./run_gunicorn.sh" volumes: - .:/code - /static:/static ports: - 443:443 extra_hosts: - "db:192.168.1.2" nginx: restart: always image: nginx:latest ports: - 80:80 volumes: - ./misc/nginx.conf:/etc/nginx/conf.d/default.conf - /static:/static depends_on: - web 

只要确保您的应用程序引用数据库为数据库,并replace我把你的主机IP的IP。

问候