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"
	}
}
相关推荐
呉師傅4 分钟前
【使用技巧】Adobe Photoshop 2024调整缩放与布局125%后出现点菜单项漂移问题的简单处理
运维·服务器·windows·adobe·电脑·photoshop
heartbeat..7 分钟前
JVM 性能调优流程实战:从开发规范到生产应急排查
java·运维·jvm·性能优化·设计规范
小章UPUP20 分钟前
Kubernetes (K8s) 与 Podman 的比较
容器·kubernetes·podman
忆~遂愿24 分钟前
CANN metadef 核心解析:计算图原型定义、算子元数据抽象与异构系统互操作机制
docker·容器
小Tomkk33 分钟前
数据库 变更和版本控制管理工具 --Bytebase 安装部署(linux 安装篇)
linux·运维·数据库·ci/cd·bytebase
赌博羊34 分钟前
ImportError: /lib/x86_64-linux-gnu/libc.so.6: version `GLIBC_2.32‘ not found
linux·运维·gnu
消失的旧时光-19431 小时前
Linux 入门核心命令清单(工程版)
linux·运维·服务器
艾莉丝努力练剑1 小时前
【Linux:文件】Ext系列文件系统(初阶)
大数据·linux·运维·服务器·c++·人工智能·算法
小天源1 小时前
Cacti在Debian/Ubuntu中安装及其使用
运维·ubuntu·debian·cacti
说实话起个名字真难啊1 小时前
用docker来安装openclaw
docker·ai·容器