使用Docker-compose在本地运行rust sqlx迁移

svdrlsy4  于 2023-02-08  发布在  Docker
关注(0)|答案(1)|浏览(196)

我正在Rust中从Zero到Prod工作,我有点偏离脚本。我正在本地停靠整个设置,包括数据库。在ENTRYPOINT上,容器调用了一个启动脚本,该脚本试图调用sqlx migrate run,导致错误./scripts/init_db.sh: line 10: sqlx: command not found
我想我已经解决了这个问题,因为我使用bullseye-slim作为运行时,它不会为最终的映像保留已安装的rust包,这有助于缩短构建时间和映像大小。
有没有一种方法可以在不安装rust、cargo等的情况下运行sqlx迁移?或者有没有一种更好的方法来完成这一点?我希望避免只是重新安装bullseye-slim映像中的所有内容,并在那里失去一些docker优化。

# Dockerfile
# .... chef segment omitted
FROM chef as builder
COPY --from=planner /app/recipe.json recipe.json
# Build our project dependencies, not our application!
RUN cargo chef cook --release --recipe-path recipe.json
# Up to this point, if our dependency tree stays the same,
# all layers should be cached.
COPY . .

ENV SQLX_OFFLINE true
# Build our project
RUN cargo build --release --bin my_app
FROM debian:bullseye-slim AS runtime
WORKDIR /app
RUN apt-get update -y \
&& apt-get install -y --no-install-recommends openssl ca-certificates \
&& apt-get install -y --no-install-recommends postgresql-client \
# Clean up
&& apt-get autoremove -y \
&& apt-get clean -y \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/my_app my_app
COPY configuration configuration
COPY scripts scripts
RUN chmod -R +x scripts
ENTRYPOINT ["./scripts/docker_startup.sh"]

docker-compose.yml如下所示

version: '3'
services:
  db:
    image: postgres:latest
    environment:
      - POSTGRES_DB=my_app
      - POSTGRES_USER=postgres
      - POSTGRES_PASSWORD=password
    ports:
      - "5432:5432"
    volumes:
      - dbdata:/var/lib/postgresql/data

  app:
    image: my_app
    environment:
      - DATABASE_URL=postgres://postgres:password@postgres:5432/my_app
    depends_on:
      - db
    ports:
      - "8080:8080"

volumes:
  dbdata:
    driver: local
vngu2lb8

vngu2lb81#

您可以在构建阶段使用货物安装来安装sqlx-cli

cargo install sqlx-cli

然后将其复制到部署阶段

COPY --from=builder $HOME/.cargo/bin/sqlx-cli sqlx-cli

或者,您可以在应用程序使用migrate!宏启动时运行迁移

sqlx::migrate!("db/migrations")
    .run(&pool)
    .await?;

相关问题