sqlx Offline Mode: Building in Docker and CI With No Database in Sight

sqlx's query! macros check every query against a live Postgres at compile time, so a plain docker build fails. How I build with SQLX_OFFLINE and a committed .sqlx folder, the .env that quietly turned it off, and the schema change that compiled fine and panicked at runtime.

Simone Negro, Backend & AI Developer
12 min read

sqlx’s query! and query_as! macros connect to Postgres while your code compiles. That is the feature: a typo in a column name is a compile error, not a 500 in production. It is also why the first docker build of a sqlx service fails, because the build stage has no database to talk to.

I set up a small axum service to see every way this goes wrong and what fixes each one. Everything below comes from that demo: sqlx 0.9.1, sqlx-cli 0.9.1, axum 0.8.9, Postgres 18, the rust:1 image (rustc 1.100.0), Docker 29.5.1. The outputs are copied from the terminal.

TL;DR
  1. Run cargo sqlx prepare against a migrated database. It writes one JSON file per query into .sqlx/. Commit that folder.
  2. In the Dockerfile build stage, set ENV SQLX_OFFLINE=true, and put .env in .dockerignore.
  3. In CI, start a throwaway Postgres, run sqlx migrate run, then cargo sqlx prepare --check. It exits non-zero when .sqlx no longer matches the code or the schema.

SQLX_OFFLINE only accepts true (any case) or 1. A DATABASE_URL without SQLX_OFFLINE=true beats the .sqlx folder every time.

The build that started this

The service has one migration (a notes table), a query_as! that lists the notes of one owner and a query! that counts them:

let notes = sqlx::query_as!(
    Note,
    "SELECT id, body FROM notes WHERE owner_id = $1 ORDER BY id",
    owner
)
.fetch_all(&pool)
.await
.unwrap();

The first Dockerfile was the one everybody writes first: COPY . ., then cargo build --release. Thirty seconds of compiling dependencies, then:

#10 31.25    Compiling notes-api v0.1.0 (/app)
#10 31.30 error: set `DATABASE_URL` to use query macros online, or run `cargo sqlx prepare` to update the query cache
#10 31.30   --> src/main.rs:12:17
#10 31.30    |
#10 31.30 12 |       let notes = sqlx::query_as!(
[...]
#10 31.32 error: could not compile `notes-api` (bin "notes-api") due to 2 previous errors

The error already names both ways out. You could give the build stage a database, but that means a Postgres reachable from docker build, with credentials, with the schema already migrated. Nobody wants that. The other way is the query cache.

How the macro decides where to look

I wanted the exact rule, not the folklore, so I read the macro source in sqlx-macros-core 0.9.1. It boils down to this:

  1. If SQLX_OFFLINE is not true and DATABASE_URL is set and not empty, go online: connect and describe the query against the real database.
  2. Otherwise, look for query-<hash of the SQL>.json in SQLX_OFFLINE_DIR first, then in .sqlx next to the crate’s Cargo.toml, then in .sqlx at the workspace root.
  3. No file found: compile error.

Two details matter. The .sqlx folder never wins over a DATABASE_URL on its own: you have to say SQLX_OFFLINE=true. And the check for “true” is literally val.eq_ignore_ascii_case("true") || val == "1", so SQLX_OFFLINE=yes is the same as not setting it. Both variables are also read from a .env file, which is where the trouble in the next section comes from.

Two 0.9 changes are worth knowing if you are upgrading. SQLX_OFFLINE_DIR from the environment now takes precedence in the macros (PR #3962), and offline became an optional feature so sqlx can build without serde (#4077). I checked the 0.9.1 Cargo.toml: the macros feature turns sqlx-core/offline on by itself, so if you use query! there is nothing to add.

cargo sqlx prepare and the .sqlx folder

I installed the CLI in a builder image with only what Postgres needs:

cargo install sqlx-cli --version 0.9.1 --no-default-features --features postgres,rustls

No --locked on purpose: the 0.9.0 changelog says cargo install --locked sqlx-cli will no longer work, because the repository stopped tracking its Cargo.lock.

Then, with DATABASE_URL pointing at the dev database:

$ sqlx migrate run
Applied 20261124000000/migrate notes (192.370742ms)
$ cargo sqlx prepare
    Checking sqlx v0.9.1
    Checking notes-api v0.1.0 (/app)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 22.31s
query data written to .sqlx in the current directory; please check this into version control

Two queries, two files, 760 and 405 bytes. Each one is what the macro would have asked Postgres: column names, types, parameter types and nullability. Here is the count(*) one, minus its last line (the hash that also names the file):

{
  "db_name": "PostgreSQL",
  "query": "SELECT count(*) AS total FROM notes",
  "describe": {
    "columns": [
      {
        "ordinal": 0,
        "name": "total",
        "type_info": "Int8",
        "origin": "Expression"
      }
    ],
    "parameters": {
      "Left": []
    },
    "nullable": [
      null
    ]
  },

nullable: null means “unknown”, and sqlx turns unknown into Option<i64>. That is why the handler says row.total.unwrap_or(0). It is also a reminder that these files are not opaque cache: they decide your Rust types, so they belong in code review like any other source file.

If your queries sit behind feature flags or in tests, the README’s form is cargo sqlx prepare -- --all-targets --all-features, and in a workspace cargo sqlx prepare --workspace writes a single .sqlx at the root.

The Dockerfile that builds with no database

FROM rust:1 AS build
WORKDIR /app
ENV SQLX_OFFLINE=true
COPY . .
RUN cargo build --release --locked

FROM debian:trixie-slim
COPY --from=build /app/target/release/notes-api /usr/local/bin/notes-api
EXPOSE 3000
CMD ["notes-api"]

And the .dockerignore, which turned out to matter as much as the ENV line:

target
.env

To be sure nothing was reachable, I stopped the Postgres container before building. The build went through, Finished release profile in 1m 10s, and the final image is 124 MB on disk. Then I started Postgres again, ran the image against it, and both endpoints answered:

[{"id":1,"body":"first"},{"id":2,"body":"second"}]
3

The .env that turned offline mode off

This is the failure I’d expect to bite people who already “did offline mode”. Most sqlx projects have a .env with DATABASE_URL=postgres://...@localhost:5432/... for local work, because sqlx-cli and the macros both read it. If the Dockerfile copies the whole context and .env is not ignored, that URL ends up inside the build stage.

I tested exactly that: .sqlx present and up to date, .env copied in, no SQLX_OFFLINE, database stopped.

#9 54.17    Compiling notes-api v0.1.0 (/app)
#9 54.26 error: error communicating with database: Connection refused (os error 111)
#9 54.26   --> src/main.rs:12:17

The cache was right there and the macro never looked at it, because rule 1 says a DATABASE_URL wins. The docs.rs page for query! says the same in its own words: omit DATABASE_URL “or else it will still try to connect”. ENV SQLX_OFFLINE=true in the Dockerfile makes the build immune to whatever .env says, and ignoring .env keeps a local password out of the build context anyway. I use both.

Running the CI check

The cache can go stale, and a stale cache doesn’t always fail loudly. That’s the job of cargo sqlx prepare --check: it re-runs the macros against a real database and compares the result with what is committed. In GitHub Actions the database is a service container:

name: ci

on:
  push:
  pull_request:

jobs:
  sqlx-metadata:
    runs-on: ubuntu-latest
    services:
      postgres:
        image: postgres:18
        env:
          POSTGRES_PASSWORD: postgres
          POSTGRES_DB: notes
        ports:
          - 5432:5432
        options: >-
          --health-cmd pg_isready
          --health-interval 5s
          --health-timeout 5s
          --health-retries 10
    env:
      DATABASE_URL: postgres://postgres:postgres@localhost:5432/notes
    steps:
      - uses: actions/checkout@v7
      - uses: dtolnay/rust-toolchain@stable
      - uses: Swatinem/rust-cache@v2
      - run: cargo install sqlx-cli --version 0.9.1 --no-default-features --features postgres,rustls
      - run: sqlx migrate run
      - run: cargo sqlx prepare --check

  docker-image:
    needs: sqlx-metadata
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v7
      - run: docker build -t notes-api .

To be honest about it: I did not run this on GitHub. I ran the same steps by hand on a Linux box, in containers: a fresh Postgres 18, sqlx migrate run, cargo sqlx prepare --check, and then the Docker build with the database stopped. The workflow file is the translation of those steps, and the action versions are the current majors as of today. On the fresh database, after both migrations of the demo (the second one comes up in the next section), the check was quiet and exited 0:

Applied 20261124000000/migrate notes (66.170648ms)
Applied 20261124000001/migrate body nullable (8.218293ms)
    Checking notes-api v0.1.0 (/app)
    Finished `dev` profile [unoptimized + debuginfo] target(s) in 0.18s

The order of the steps is the point. sqlx migrate run before the check means the database has the schema that is in the repository, not whatever an old dev database happens to have. The second job builds the image exactly like production does, with no database at all. If the first job passes, the second can’t fail on sqlx.

Breaking it on purpose

A changed query

I changed ORDER BY id to ORDER BY id DESC and did not re-run prepare. The SQL text changed, so its hash changed, so there is no file for it. The Docker build:

#10 60.97    Compiling notes-api v0.1.0 (/app)
#10 61.12 error: `SQLX_OFFLINE=true` but there is no cached data for this query, run `cargo sqlx prepare` to update the query cache or unset `SQLX_OFFLINE`
#10 61.12   --> src/main.rs:12:17

And the CI check, exit code 1:

error: prepare check failed: .sqlx is missing one or more queries; you should re-run sqlx prepare

This is the easy case. Even without CI you’d find out at the first build.

A changed schema

The case that worried me is the one where the Rust code does not change. I added a second migration:

ALTER TABLE notes ALTER COLUMN body DROP NOT NULL;

The query text is identical, so the hash is identical, and the old JSON file still says body is not nullable. The offline Docker build passed without a warning. Then I ran the new image (which applied the migration at startup), inserted a note with a NULL body, and called the endpoint:

thread 'tokio-rt-worker' (17) panicked at src/main.rs:19:6:
called `Result::unwrap()` on an `Err` value: ColumnDecode { index: "1", source: UnexpectedNullError }

The request got no response at all. The compile time check that is the whole reason to use query! had been checking against a schema that no longer existed. This is the failure a stale .sqlx produces in practice, and no build without a database can see it.

cargo sqlx prepare --check, run against the migrated database, did see it. It did not even get as far as comparing files: in live mode the macro now generated Option<String> for body, and my struct said String:

error[E0277]: the trait bound `std::string::String: From<std::option::Option<std::string::String>>` is not satisfied
  --> src/main.rs:12:17
[...]
error: `cargo check` failed with status: exit status: 101

In the same run rustc 1.100.0 also hit an internal compiler error in its incremental cache, next to the real error. cargo clean -p notes-api made it go away, and it has nothing to do with sqlx, but I mention it because it makes the CI log look scarier than it is.

After changing the field to body: Option<String>, the check failed one more time, now for the reason I expected:

error: prepare check failed: one or more query files differ (query-25b5d003dde43dce6297a11abc579f0ca205f80e3148a2f2fc93c76bd39fdc84.json); you should re-run sqlx prepare

The difference between the old file and the new one was a single line, false becoming true in the nullable array. cargo sqlx prepare, then --check again: exit code 0.

Here is everything I tried in one place. Each row is a separate run; the three rows about the value of SQLX_OFFLINE were a cargo check in the builder container rather than a full Docker build, with nothing listening at that URL.

Build-time setup.sqlxResult
no DATABASE_URL, no SQLX_OFFLINEabsentcompile error: set DATABASE_URL or run prepare
SQLX_OFFLINE=true, .env ignoredcurrentbuilds, image works
.env copied in, no SQLX_OFFLINE, DB downcurrentcompile error: Connection refused
SQLX_OFFLINE=true plus a DATABASE_URL to nowherecurrentbuilds
SQLX_OFFLINE=1 plus the same DATABASE_URLcurrentbuilds
SQLX_OFFLINE=yes plus the same DATABASE_URLcurrentcompile error: Connection refused
SQLX_OFFLINE=true, query text editedstalecompile error: no cached data for this query
SQLX_OFFLINE=true, column made nullablestalebuilds, then panics on the first NULL
prepare --check after that migrationstaleE0277 until the struct is fixed, then “query files differ”

Making rebuilds bearable with cargo-chef

Offline mode solves the database problem, not the speed problem. With COPY . . before cargo build, any edit to main.rs invalidates the layer and every dependency compiles again. cargo-chef splits the build so dependencies sit in their own layer:

FROM rust:1 AS chef
RUN cargo install cargo-chef --version 0.1.78 --locked
WORKDIR /app

FROM chef AS planner
COPY . .
RUN cargo chef prepare --recipe-path recipe.json

FROM chef AS build
COPY --from=planner /app/recipe.json recipe.json
RUN cargo chef cook --release --locked --recipe-path recipe.json
COPY . .
ENV SQLX_OFFLINE=true
RUN cargo build --release --locked

The cook step only compiles dependencies, and sqlx-macros is a dependency there, not something that runs, so it does not need SQLX_OFFLINE. I put the ENV after cook so it sits with the step that needs it. The recipe.json only describes manifests, so a change in .sqlx or in your SQL does not invalidate the cooked layer either.

I timed both Dockerfiles after a one-line change to main.rs, three times each, with the database stopped:

DockerfileFirst buildRebuilds after editing main.rsMedian rebuild
plain, COPY . . then build84.9 s90.2 s, 79.2 s, 66.6 s79.2 s
cargo-chef152.2 s21.3 s, 23.2 s, 20.9 s21.3 s

These are wall-clock times for the whole docker build, image export included, on a 12-core x86_64 Linux box that other jobs were using at the same time, which is why the plain rebuilds wander by 24 seconds. The chef rebuilds are steady because they do much less: the cook layer comes from cache and the final cargo build takes 6 to 8 seconds, against 54 to 74 seconds when everything compiles. The first chef build is slower because it also compiles cargo-chef itself; you pay that once per builder cache.

I also checked the .sqlx claim from above: I added a newline to one of the JSON files and rebuilt with chef. The cook step was CACHED, and only the last cargo build ran.

The build role is not the runtime role

One thing the demo glosses over: it uses the postgres superuser everywhere, for prepare, for the CI check, for migrations at startup. That is fine for a throwaway CI database and wrong for anything else. The database that prepare and --check talk to only needs the schema, never real data, so it should be a disposable container with throwaway credentials, and those credentials should never reach the image. At runtime the service should log in as a role that can’t do much, which is a topic of its own: I wrote down the three roles I use for a Rust backend with sqlx. Offline mode is what makes that split clean, because the build no longer needs any role at all.

The other half is making the binary fail fast when the runtime config is wrong, so a missing DATABASE_URL is a clear startup error instead of a panic deep in a handler. I covered that in refusing to start with a bad config file, and the image above also wants the graceful shutdown on SIGTERM before it goes anywhere near an orchestrator.

Verdict

Offline mode is one environment variable, and that is the misleading part. SQLX_OFFLINE=true makes the build pass, and a build that passes against stale metadata is worse than one that fails, because it moves the error from compile time to the first NULL in production. So my rule is: SQLX_OFFLINE=true goes in the Dockerfile and nowhere else, local development stays online against a real database, and cargo sqlx prepare --check after sqlx migrate run is a required CI job, not a nice-to-have. Without that job I would rather not use the macros at all.

What I haven’t settled is how to keep .sqlx from becoming merge-conflict bait on a busy repository, since every query change touches a file named after a hash. On a one-person project it hasn’t come up yet.

References