docker-compose.yml
version: '3.4'
services:
db:
container_name: pg
image: postgres:latest
environment:
TZ: Asia/Shanghai
POSTGRES_PASSWORD: postgres
ports:
- 5432:5432
volumes:
- ./data:/var/lib/postgresql/data
- ./etc/initdb:/docker-entrypoint-initdb.d
restart: always
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $DB_USERNAME -d $DB_DATABASE"]
interval: 10s
timeout: 5s
retries: 5
etc/initdb/init-user-db.sh( chmod 需要可执行权限)
#!/bin/bash
set -e
psql -v ON_ERROR_STOP=1 --username "$POSTGRES_USER" --dbname "$POSTGRES_DB" <<-EOSQL
CREATE USER test WITH PASSWORD '123456';
CREATE DATABASE testdb;
GRANT ALL PRIVILEGES ON DATABASE testdb TO test;
EOSQL
.env
DB_HOST=localhost
DB_PORT=5432
DB_USERNAME=test
DB_PASSWORD=123456
DB_DATABASE=testdb
datasource.ts
import { DataSource, DataSourceOptions } from "typeorm"
import * as envConfig from 'dotenv'
envConfig.config()
const options: DataSourceOptions = {
type: "postgres",
host: process.env.DB_HOST,
port: Number(process.env.DB_PORT),
username: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE,
entities: [],
migrations: [],
migrationsRun: true,
synchronize: false, // 使用 migration
logging: false,
}
export const AppDataSource = new DataSource(options)
app.ts
// 尽早导入 env 变量
import * as envConfig from 'dotenv'
envConfig.config()
import { AppDataSource } from './datasource'
AppDataSource.initialize()
.then(() => {
// start server
})
.catch(error => console.log('database connected failure.', error))