Go语言 在Docker容器中不创建数据库迁移

8fq7wneg  于 2023-08-01  发布在  Go
关注(0)|答案(2)|浏览(107)

谁能说说为什么我的迁移没有在docker容器中创建?本地我有一个工作项目,但在容器中没有表。我的表是在本地创建的,但当我运行docker-compose时,控制台日志中没有迁移
我的Dockerfile:

FROM golang:1.17-alpine as build-stage

RUN mkdir -p /app

WORKDIR /app

COPY . /app
RUN go mod download

RUN go build -o crypto main.go

FROM alpine:latest

WORKDIR /

COPY --from=build-stage /app/crypto .

EXPOSE 9999

ENTRYPOINT [ "/crypto" ]

字符串
docker-compose.yml

version: "3"

volumes:
  crypto_postgres_data: {}

services:
  crypto:
    build:
      context: .
      dockerfile: ./Dockerfile
    image: crypto_app
    platform: linux/amd64
    env_file:
      - ./.env
    depends_on:
      - postgres
    ports:
      - "9999:9999"

  postgres:
    image: postgres:14.2 
    healthcheck:
      test: [ "CMD", "pg_isready", "-U", "$POSTGRES_USER", "-d", "$POSTGRES_DB" ]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    restart: unless-stopped
    env_file:
      - ./.env 
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 4G
    volumes:
      - crypto_postgres_data:/var/lib/postgresql/data:Z
  migrate:
    image: migrate/migrate
    volumes:
      - .:/migrations
My output in container:
[gomigrate] 2022/06/22 14:02:11 Migrations path: migrations/
[gomigrate] 2022/06/22 14:02:11 Migrations table not found
[gomigrate] 2022/06/22 14:02:11 Created migrations table: gomigrate
[gomigrate] 2022/06/22 14:02:11 Migrations file pairs found: 0

提前致谢

oaxa6hgo

oaxa6hgo1#

您的迁移服务没有任何命令,因此无法迁移迁移文件夹中的数据。你应该像这样改变它:

version: "3"

volumes:
  crypto_postgres_data: {}

services:
  crypto:
    build:
      context: .
      dockerfile: ./Dockerfile
    image: crypto_app
    platform: linux/amd64
    env_file:
      - ./.env
    depends_on:
      - postgres
    ports:
      - "9999:9999"
    networks:
      - crypto

  postgres:
    image: postgres:14.2 
    healthcheck:
      test: [ "CMD", "pg_isready", "-U", "$POSTGRES_USER", "-d", "$POSTGRES_DB" ]
      interval: 10s
      timeout: 5s
      retries: 5
      start_period: 10s
    restart: unless-stopped
    env_file:
      - ./.env 
    deploy:
      resources:
        limits:
          cpus: '1'
          memory: 4G
    volumes:
      - crypto_postgres_data:/var/lib/postgresql/data:Z
    networks:
      - crypto

  migrate:
    image: migrate/migrate
    restart: on-failure:5 
    env_file:
      - ./.env 
    volumes:
      - ./migrations:/migrations
    command: ["-path", "/migrations", "-database",  "postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable", "up"]
    depends_on:
      - db
    networks:
      - crypto

networks:
  crypto:
    driver: bridge

字符串
参考:How to run golang-migrate with docker-compose?

1rhkuytd

1rhkuytd2#

在我看来,最好使用volume选项,其中migrateservicedocker-compose文件中。
您可以轻松地创建迁移文件,而无需使用像here这样的长命令,也无需使用docker
你可以看看here的例子。此外,该项目还展示了如何使用运行postgres服务的docker-compose来运行迁移文件。

相关问题