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"
	}
}
相关推荐
!chen10 分钟前
linux服务器静默安装Oracle26ai
linux·运维·服务器
莫大33013 分钟前
2核2G云服务器PHP8.5+MySQL9.0+Nginx(LNMP)安装WordPress网站详细教程
运维·服务器·nginx
刚刚入门的菜鸟15 分钟前
php-curl
运维·web安全·php
REDcker28 分钟前
Linux 文件描述符与 Socket 选项操作详解
linux·运维·网络
2501_927773071 小时前
imx6驱动
linux·运维·服务器
hy____1231 小时前
Linux_进程间通信
linux·运维·服务器
啦啦啦小石头1 小时前
Docker 换源
docker
银发控、1 小时前
nginx静态资源
运维·nginx
老百姓懂点AI1 小时前
[测试工程] 告别“玄学”评测:智能体来了(西南总部)基于AI agent指挥官的自动化Eval框架与AI调度官的回归测试
运维·人工智能·自动化
德育处主任Pro2 小时前
『NAS』用SSH的方式连上NAS
运维·ssh