docker 启动 postgres 15 设置密码为:zR6c49Mmmf4Rc6Vk请帮我写出docker-compose 配置。并使用python 测试连接 postgres 数据库和在容器内测试是否能连接postgres
version: '3.9'
services: db: image: postgres:15 restart: always environment: POSTGRES_PASSWORD: zR6c49Mmmf4Rc6Vk ports: - "5432:5432"
在python中测试连接postgres数据库:
import psycopg2
try:
connection = psycopg2.connect(user="postgres",
password="zR6c49Mmmf4Rc6Vk",
host="localhost",
port="5432",
database="postgres")
cursor = connection.cursor()
print(connection.get_dsn_parameters(), "\n")
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record, "\n")
except (Exception, psycopg2.Error) as error:
print("Error while connecting to PostgreSQL", error)
finally:
if connection:
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
在docker容器中测试连接postgres数据库:
docker exec -it <container_name> bash
psql -U postgres -h localhost
如果出现如下提示,证明连接成功:
Password for user postgres:
psql (15.0 (Debian 15.0-1.pgdg110+1))
Type "help" for help.
postgres=#
原文地址: https://www.cveoy.top/t/topic/bSyL 著作权归作者所有。请勿转载和采集!