This guide describes how to set up and run a Rust (Actix Web + SQLx) backend with PostgreSQL using Docker Compose.
1.1 Start PostgreSQL container:
docker compose up -d db --build- Image:
postgres:latest - Default port:
5432 - Default username:
postgres - Default password:
postgres - Default database:
aihub
2.1 Set the DATABASE_URL for your current shell session:
export DATABASE_URL=postgres://postgres:postgres@localhost:5432/aihubThis variable will be lost after the shell session ends. When running inside Docker, the host should be
dbinstead oflocalhost.
Format:
postgres://<username>:<password>@<host>:<port>/<database_name>
cargo install sqlx-cli --no-default-features --features native-tls,postgresRequired for creating migrations, running them, and generating offline query cache.
4.1 Create a new migration file with a timestamp:
sqlx migrate add init- Run this in the same directory as
Cargo.toml. - The migration files will be stored in the
./migrationsdirectory.
4.2 Edit the generated .sql file to add your SQL schema.
sqlx database createThis creates the
aihubdatabase specified inDATABASE_URL.
sqlx migrate runApplies all pending migrations to your database.
If you use:
SQLX_OFFLINE=truein your shell session, orENV SQLX_OFFLINE=truein your Dockerfile
You must generate the offline cache before building the Docker image:
cargo sqlx prepare -- --bin aihubThis will create the .sqlx/ directory containing the query metadata required for offline builds.
docker compose up api --buildThis will build and run the backend service defined in
docker-compose.yml.
-
Local vs. Docker network: When running inside Docker, use
db(the Docker Compose service name) as the database host instead oflocalhost. -
SQLx offline mode: If you forget to run
cargo sqlx preparebefore building withSQLX_OFFLINE=true, the build will fail with "no.sqlxdata found". -
Rebuilding after migrations: If your SQL schema changes, regenerate the offline cache before rebuilding the Docker image.
-
Multiple environments: For development, use a
.env.devfile and load it withdotenvorenv_fileindocker-compose.yml.
fish shell: env (cat .env.dev | grep -v '^#' | xargs) && cargo run
bash shell: export $(grep -v '^#' .env.dev | xargs) && cargo run
bash shell: export $(grep -v '^#' .env.dev | xargs) && cargo run
command: psql progresql://progresql:progresql@localhost:5432/aihub
Inside Docker: docker exec -it aihub-db-1 psql -U postgres -d aihub