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"
	}
}
相关推荐
研华嵌入式1 分钟前
Ubuntu 20.04 停止支持怎么办?
linux·运维·ubuntu
野熊佩骑20 分钟前
一文读懂运维监控之 Ubuntu22.04安装部署Zabbix监控
linux·运维·服务器·网络·ubuntu·zabbix·database
特立独行的猫a30 分钟前
PostgreSQL客户端工具介绍:从性能测试到跨平台管理
数据库·docker·postgresql·客户端·pgadmin4
AI视觉网奇32 分钟前
audio2face docker方式
docker·ue5
双层吉士憨包39 分钟前
Claude账号共享教程分享
运维·服务器
lllsure1 小时前
Linux 日志管理
linux·运维·服务器
yewq-cn2 小时前
自动更新 Docker 镜像
运维·docker·容器
haluhalu.2 小时前
Linux系统下进程池设计与实现详解
linux·运维·服务器
m0_537473492 小时前
Nginx 生产环境平滑升级实战:从 1.24.0 到 1.28.0 的零宕机操作全记录
运维·nginx
虹梦未来2 小时前
【运维】Ubuntu2404使用新风格更新镜像源
运维·服务器