docker 安装postgres,nodejs连接pg
docker pull Postgres
docker image ls
docker pull dpage/pgadmin4
docker volume create postgres-volume
docker run -d -p 5432:5432 ---name postresql -v Postgres-volume:/var/lib/portgresql/data -e POSTGRES_PASSWORD=portgresPW postgres
docker run -d -p 5433:80 ---name pgadmin4 -e PGADMIN_DEFAULT_EMAIL=test@qq.com -e PGADMIN_DEFAULT_PASSWORD=123456 dpage/pgadmin4
数据库管理后台访问pgadmin4:
用户名:test@qq.com
密码:123456
连接数据库
主机名:host.docker.internal(默认)
用户名:portgres(默认)
密码:portgresPW
pnpm install pg config
config/default.json
json
{
"db":{
"user": "postgres",
"host": "127.0.0.1",
"database": "postgres",
"password": "pass123",
"port": "5432"
}
}
index.js
js
import pg from "pg"
import config from "config"
const { Client } = pg
const dbConfig = config.db
const pgClient = new Client(dbConfig)
//1.连接到数据库
pgClient.connect((connectErr) => {
if (connectErr) {
console.error(connectErr,"连接失败")
return
}
console.log("连接成功")
//2.执行查询
pgClient.query('SELECT * from tbl_user where username = $1', ['testuser'], (queryErr, res) => {
if (!queryErr) {
console.log(res.rows[0])
} else {
console.error(queryErr,"查询失败")
}
//3.关闭连接
pgClient.end((endErr) => {
if (endErr) {
console.error(err,"关闭连接失败")
}else{
console.log("关闭连接")
}
})
})
})
package.json
json
{
"name": "postgres-demo",
"version": "1.0.0",
"description": "",
"main": "./src/index.js",
"author": "hjj",
"license": "ISC",
"type": "module",
"scripts": {
"dev": "node ./src/index.js"
},
"dependencies": {
"config": "^3.3.12",
"pg": "^8.12.0"
}
}