Connecting to Postgresql in a docker container from outside

后端 未结 14 1820
太阳男子
太阳男子 2020-11-29 14:42

I have Postgresql on a server in a docker container. How can I connect to it from the outside, that is, from my local computer? What setting should I apply to allow that?

相关标签:
14条回答
  • 2020-11-29 15:16

    first open the docker image for the postgres

    docker exec -it <container_name>
    

    then u will get the root --root@868594e88b53:/# it need the database connection

    psql postgresql://<username>:<databasepassword>@postgres:5432/<database>
    
    0 讨论(0)
  • 2020-11-29 15:17

    You can run Postgres this way (map a port):

    docker run --name some-postgres -e POSTGRES_PASSWORD=mysecretpassword -d -p 5432:5432 postgres
    

    So now you have mapped the port 5432 of your container to port 5432 of your server. -p <host_port>:<container_port> .So now your postgres is accessible from your public-server-ip:5432

    To test: Run the postgres database (command above)

    docker ps
    CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS              PORTS                     NAMES
    05b3a3471f6f        postgres            "/docker-entrypoint.s"   1 seconds ago       Up 1 seconds        0.0.0.0:5432->5432/tcp    some-postgres
    

    Go inside your container and create a database:

    docker exec -it 05b3a3471f6f bash
    root@05b3a3471f6f:/# psql -U postgres
    postgres-# CREATE DATABASE mytest;
    postgres-# \q
    

    Go to your localhost (where you have some tool or the psql client).

    psql -h public-ip-server -p 5432 -U postgres
    

    (password mysecretpassword)

    postgres=# \l
    
                                 List of databases
       Name    |  Owner   | Encoding |  Collate   |   Ctype    |   Access privileges
    -----------+----------+----------+------------+------------+-----------------------
     mytest    | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
     postgres  | postgres | UTF8     | en_US.utf8 | en_US.utf8 |
     template0 | postgres | UTF8     | en_US.utf8 | en_US.utf8 | =c/postgres   
    

    So you're accessing the database (which is running in docker on a server) from your localhost.

    In this post it's expained in detail.

    0 讨论(0)
提交回复
热议问题