docker 安装postgres,nodejs连接pg

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:

http://localhost:5433

用户名: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"
	}
}
相关推荐
sxgzzn5 小时前
光伏数智化综合平台:让光伏电站运维更智能、更高效
运维
乌托邦的逃亡者6 小时前
Linux中如何检测IP冲突
linux·运维·tcp/ip
一曦的后花园7 小时前
linux搭建promethes并对接node-exporter指标
linux·运维·服务器
乌托邦的逃亡者7 小时前
CentOS/Openeuler主机中,为一个网卡设置多个IP地址
linux·运维·网络·tcp/ip·centos
拾贰_C8 小时前
【OpenClaw | openai | QQ】 配置QQ qot机器人
运维·人工智能·ubuntu·面试·prompt
桌面运维家8 小时前
服务器进程异常监控:快速定位与排障实战指南
运维·服务器
Java后端的Ai之路8 小时前
Kubernetes是什么?(小白入门版)
云原生·容器·kubernetes·教程
风曦Kisaki8 小时前
# Linux Shell 编程入门 Day02:条件测试、if 判断、循环与随机数
linux·运维·chrome
木雷坞8 小时前
视觉算法环境 Docker 镜像拉取失败排查
运维·人工智能·docker·容器
郝亚军8 小时前
ubuntu 22.04如何安装libmodbus
运维·服务器·ubuntu