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"
	}
}
相关推荐
yiSty8 分钟前
linux命令行下使用百度云网盘【自用】
linux·运维·百度云
是小崔啊1 小时前
叩丁狼k8s - 组件篇
云原生·容器·kubernetes
txzz88881 小时前
CentOS-Stream-10 搭建YUM源Web服务器
linux·运维·centos·yum源·linux系统更新·centos系统更新·自建web yum源
天下不喵1 小时前
python项目部署之pytandic与.env的使用教程
python·docker
我科绝伦(Huanhuan Zhou)1 小时前
Linux系统硬件时钟与系统时钟深度解析及同步实操指南
linux·运维·服务器
k***92162 小时前
【Linux】进程概念(六):地址空间核心机制
linux·运维·算法
保持低旋律节奏2 小时前
linux——进程调度(时间片+优先级轮转调度算法O(1))
linux·运维·算法
Dobby_052 小时前
【k8s】集群安全机制(二):鉴权
运维·安全·kubernetes
芥子沫2 小时前
Docker安装Blossom笔记
笔记·docker·容器
A13247053122 小时前
SSH远程连接入门:安全高效地管理服务器
linux·运维·服务器·网络·chrome·github