简体   繁体   中英

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. Tests were successful. The data came, the database was updated.

The next step was to place this script in the docker container. Dockerfile and Docker-Compose.yml are attached below. I add environment with working programs to the container through Volume. The docker container runs on the local machine where the postgres data base is located. 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.

How can I solve the problem of connecting the docker container to a locally located database?

=---------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. In colloquial terms, "localhost" refers to "this computer" or "the computer I am working on". All requests to localhost will be redirected back to any processes listening on the localhost interface. Inside a container, the localhost interface is different from that of localhost outside the container. In this case, you should consider making your database either listen on 0.0.0.0 or your machine's IP address. Then, from within the container, you can connect to your database using your machine's IP address.

Hope this helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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