简体   繁体   English

从Docker容器连接到本地postgres数据库

[英]Connecting to the local postgres database from the Docker container

My task was to write a script that received information from a remote computer and recorded the received information on a locally located Postgres DataBase. 我的任务是编写一个脚本,从远程计算机接收信息,并将收到的信息记录在本地的Postgres数据库中。 Tests were successful. 测试成功了。 The data came, the database was updated. 数据来了,数据库已更新。

The next step was to place this script in the docker container. 下一步是将此脚本放在docker容器中。 Dockerfile and Docker-Compose.yml are attached below. Dockerfile和Docker-Compose.yml附在下面。 I add environment with working programs to the container through Volume. 我通过Volume将环境与工作程序添加到容器中。 The docker container runs on the local machine where the postgres data base is located. docker容器在postgres数据库所在的本地计算机上运行。 When I run the image, I control the workflow of the program and watch the data being received from the remote computer, but writing messages to the postgres data base at the address - postgres + psycopg2: // postgres: hi123 @ localhost: 5432 / Back does not occur. 当我运行图像时,我控制程序的工作流程并观察从远程计算机接收的数据,但是将消息写入地址的postgres数据库 - postgres + psycopg2: // postgres: hi123 @ localhost: 5432 /返回不会发生。

How can I solve the problem of connecting the docker container to a locally located database? 如何解决将docker容器连接到本地数据库的问题?

=---------Dockerfile---------=
FROM python:latest
WORKDIR /backend
COPY requirements.txt /backend/
RUN pip install -r requirements.txt
=----------------------------=

=-----Docker-compose.yml-----=
    version: '3'

    services:
      back:
        image: git_rep_2_back:latest
        environment:
          - PYTHONPATH=/backend/
        volumes:
          - "./Platform:/backend"
        command: bash -c "cd server && python launcher.py"
=-----------------------------=

=-------configfile_for_connection_to_database-------=

postgres+psycopg2://postgres:hi123@localhost:5432/Back

=---------------------------------------------------=

The problem is that you are trying to connect to "localhost" from within the container. 问题是您正在尝试从容器内连接到“localhost”。 In colloquial terms, "localhost" refers to "this computer" or "the computer I am working on". 在口语中,“localhost”指的是“这台计算机”或“我正在处理的计算机”。 All requests to localhost will be redirected back to any processes listening on the localhost interface. 对localhost的所有请求都将重定向回在localhost接口上侦听的任何进程。 Inside a container, the localhost interface is different from that of localhost outside the container. 内的容器,该localhost接口是从不同的localhost在容器的外部。 In this case, you should consider making your database either listen on 0.0.0.0 or your machine's IP address. 在这种情况下,您应该考虑让数据库监听0.0.0.0或您机器的IP地址。 Then, from within the container, you can connect to your database using your machine's IP address. 然后,从容器中,您可以使用计算机的IP地址连接到数据库。

Hope this helps! 希望这可以帮助!

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

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