Diesel, docker and diesel setup for postgresql

when I build a docker image I have given the following commands

FROM rust

RUN apt update
RUN apt install -y libpq-dev

RUN cargo install diesel_cli --no-default-features --features postgres

WORKDIR /usr/src/actix-tera-test

COPY . .

# RUN diesel setup

RUN cargo install --path .

EXPOSE 8000

CMD ["actix-tera-test"]

I thought because the docker-compose.yml creates a new network with the folder name, I can run diesel setup by specifying DATABAS_URL in environment

my docker-compose.yml file is

version: "3"

services:
    db:
        environment:
            POSTGRES_USER: "postgres"
            POSTGRES_DB: "studentdb"
            POSTGRES_PASSWORD: "password"
        image: postgres:latest
        ports:
        - "7000:5432"

    web:
        restart: on-failure
        depends_on:
            - db
        build: .
        environment: 
            DATABASE_URL: "postgres://postgres:password@db/studentdb"
        ports:
            - "8000:8000"

I want to run diesel setup as only the db is created when postgres container is pulled, not the tables .... how do I do it?
Thank You

ok, found a solution (non-elegant, but works)

so the command option (CMD) runs once the images are built. Basically, it runs when the networks are all set up. But there is one issue, the postgres image is yet to run and setup the server yet.
So, the option of restart: on-failure will come to use here. The web (one with diesel) container keeps on restarting until db (postgres) container is setup properly. Once postgres runs properly, the diesel migration also runs properly.

here is the Dockerfile

FROM rust

RUN apt update
RUN apt install -y libpq-dev

RUN cargo install diesel_cli --no-default-features --features postgres

WORKDIR /usr/src/actix-tera-test

COPY . .

RUN cargo install --path .

CMD bash -c "diesel setup && actix-tera-test"

and here is the docker-compose.yml file

version: "3"

services:
    db:
        environment:
            POSTGRES_USER: "postgres"
            POSTGRES_DB: "studentdb"
            POSTGRES_PASSWORD: "password"
        image: postgres:latest
        expose:
            - 5432

    web:
        restart: on-failure
        depends_on:
            - db
        environment: 
            DATABASE_URL: "postgres://postgres:password@db/studentdb"
        build: .
        ports:
            - 8000:8000
        links:
            - db

As you already noticed your database is not available at the time your are building your container. Another way to circumvent this issue is to include your migrations into the final binary by using the diesel_migrations::embed_migrations! macro. This allows you to just apply migrations as part of the application startup and does remove the need to install diesel_cli inside of your production container.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.