简体   繁体   English

无法连接到本地 postgres 容器

[英]cannot connect to local postgres container

I am new to docker and postgres and this is really puzzling to me.我是 docker 和 postgres 的新手,这让我很困惑。 After pulling the postgres 14.1 alpine image, I created a container from the image called postgres14.1 setting the user and password:拉取 postgres 14.1 alpine 镜像后,我从名为 postgres14.1 的镜像创建了一个容器,并设置了用户和密码:

docker run --name postgres14.1 -p 5432:5432 -e POSTGRES_USER=root -e POSTGRES_PASSWORD=secret -d postgres:14.1-alpine

Then I created a database called 'simple_bank' on the container:然后我在容器上创建了一个名为“simple_bank”的数据库:

docker exec -it postgres14.1 createdb --username=root --owner=root simple_bank

Before connecting to the database in TablePlus or VSCode with postgres extension, I tried to access in the terminal:在使用 postgres 扩展连接到 TablePlus 或 VSCode 中的数据库之前,我尝试在终端中访问:

docker exec -it postgres14.1 psql simple_bank

And it works fine.它工作正常。 In the terminal, \du+ confirms root is indeed a superuser in the simple_bank database:在终端中, \du+确认root确实是simple_bank数据库中的超级用户:

Role name |                         Attributes                         | Member of | Description 
-----------+------------------------------------------------------------+-----------+-------------
 root      | Superuser, Create role, Create DB, Replication, Bypass RLS | {}        | 

Then I tried to connect via TablePlus with the following config:然后我尝试通过 TablePlus 使用以下配置进行连接:

Host/Socket: 127.0.0.1
Port:5432
User:root
Password:secret
Database:root

This can't be connected saying role root doesn't exit.这无法连接说角色root不退出。 If leave the user blank and set database to postgres then it connects but it can't find the simple_bank database created from the command line.如果将用户留空并将数据库设置为postgres ,则它会连接,但无法找到从命令行创建的simple_bank数据库。

In the end, the problem is because I already have a local instance of postgres installed and it by default also connects to port 5432 on my local machine.最后,问题是因为我已经安装了 postgres 的本地实例,并且默认情况下它也连接到我本地机器上的端口 5432。 Hence in creating the postgres container, I need to choose a different port on local host.因此在创建 postgres 容器时,我需要在本地主机上选择一个不同的端口。 So changing the below docker command and then connect locally using port 5433 fixes the problem.因此,更改以下 docker 命令,然后使用端口 5433 在本地连接可以解决问题。

docker run --name postgres14.1 -p 5433:5432 -e POSTGRES_USER=root -e POSTGRES_PASSWORD=secret -d postgres:14.1-alpine

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

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