我在Docker内部的Golang上编写的两个应用程序之间迁移PostgreSQL时遇到了问题. 只创建了一个表,该表首先通过Docker容器migrations.
我使用迁移工具.第一个应用程序是"项目",第二个应用程序是"订单".在这些应用程序的每个目录中都有"迁移"文件夹.在"Projects/migrations"中分别有001_tag_items_up.sql和"down",在"order/migrations"中有001_create_order_up. sql.If start the "items" container first, the table for "order" will not be created and vice versa.
001_CREATE_ITEMS_up.sql
CREATE TABLE IF NOT EXISTS items (
id SERIAL PRIMARY KEY,
name VARCHAR(255) NOT NULL,
description TEXT,
price DECIMAL NOT NULL
);
001_create_order_up.sql
CREATE TABLE IF NOT EXISTS orders (
id SERIAL PRIMARY KEY,
item_id INT NOT NULL,
quantity INT DEFAULT 1
);
两个应用的Dockerfile
FROM golang:1.22 as builder
WORKDIR /app
COPY go.mod go.sum ./
RUN go mod download
COPY . .
RUN CGO_ENABLED=0 GOOS=linux go build -o service .
FROM alpine:latest
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /app/service .
COPY --from=builder /app/migrations /root/migrations
CMD ["./service"]
docker—compose
version: '3.8'
services:
postgres:
image: postgres:13
environment:
POSTGRES_USER: user
POSTGRES_PASSWORD: password
POSTGRES_DB: dbname
ports:
- "5432:5432"
volumes:
- /database:/var/lib/postgresql_data
items-service:
build:
context: /items
dockerfile: Dockerfile
depends_on:
- postgres
orders-service:
build:
context: /order
dockerfile: Dockerfile
depends_on:
- postgres
应用程序的代码"项目"和"订单"
package main
import (
"log"
"github.com/golang-migrate/migrate/v4"
_ "github.com/golang-migrate/migrate/v4/database/postgres"
_ "github.com/golang-migrate/migrate/v4/source/file"
)
func main() {
m, err := migrate.New(
"file://migrations",
"postgres://user:password@postgres:5432/dbname?sslmode=disable",
)
if err != nil {
log.Fatalf("migration failed to initialize: %v", err)
}
if err := m.Up(); err != nil && err != migrate.ErrNoChange {
log.Fatalf("migration failed: %v", err)
}
}