A new release of an application often needs a new database schema. If the new pods start before the schema change lands, they crash or return errors until someone runs the migration by hand. Argo CD can run that migration for you as part of every sync, using a Kubernetes Job marked as a PreSync hook.
This guide builds that setup step by step with golang-migrate and PostgreSQL. The Argo CD parts work the same with Flyway, Alembic, Rails or any other tool that runs in a container. The behaviour described here follows the Argo CD 3.6 documentation on sync phases and waves.
How a sync runs hooks
Argo CD splits every sync into phases. A resource joins a phase through the argocd.argoproj.io/hook annotation, and anything without that annotation belongs to the Sync phase. The phases you will use most are PreSync, Sync, PostSync and SyncFail.
Argo CD applies all PreSync hooks first. If any of them fails, the sync stops and is marked as failed, so your Deployment is never updated. Only when every PreSync hook has succeeded does Argo CD move on to the Sync phase, where your normal manifests are applied. PostSync hooks run after that, once the sync succeeded and every resource is Healthy. SyncFail hooks run when the sync operation fails.
Inside each phase, sync waves set the order. The argocd.argoproj.io/sync-wave annotation takes an integer, lower waves go first, and the default is wave 0. When two resources share a phase and wave, Argo CD sorts them by kind (namespaces first, custom resources last) and then by name. Between waves the controller waits 2 seconds by default, which you can change with controller.sync.wave.delay.seconds in argocd-cmd-params-cm.
For a migration this ordering is exactly what you want. The Job runs in PreSync, and the new Deployment only rolls out if the Job exits with code 0.
Step 1: package the migrations in an image
The hook Job needs the migration files and the tool that applies them. The simplest approach is a small image built on top of the official migrate/migrate image, with your SQL files copied in. Build it in the same pipeline that builds the application image and give it the same tag, so a given commit always ships matching code and schema.
golang-migrate expects files named {version}_{title}.up.sql and {version}_{title}.down.sql. A directory might look like this:
migrations/
000001_create_orders.up.sql
000001_create_orders.down.sql
000002_add_orders_status.up.sql
000002_add_orders_status.down.sql
The Dockerfile only adds those files to the upstream image. Its entrypoint is already the migrate binary, so the Job can pass arguments directly.
FROM migrate/migrate:v4.20.1
COPY migrations /migrations
docker build -t registry.example.com/shop/migrations:1.8.0 .
docker push registry.example.com/shop/migrations:1.8.0
golang-migrate records the applied version in a table in the target database (schema_migrations for PostgreSQL unless you change it). That matters later, because Argo CD will run this Job on every sync and the tool must skip work it has already done.
Step 2: keep the database credentials outside the Application
This step prevents the most common failure with migration hooks. A PreSync hook is applied before everything in the Sync phase, and that includes Secrets that belong to the same Application. If the Job reads its password from a Secret that sits next to it in Git, the Job sees the old password during a rotation, or fails outright on the first sync when the Secret does not exist yet.
There are two fixes. You can manage the Secret outside this Application, for example with a separate Application, an External Secrets setup or a one-time kubectl command. Or you can turn the Secret into a hook as well and give it a lower sync wave, so it is applied before the Job.
The first option is easier to reason about. For a test cluster, create the Secret once by hand:
kubectl create namespace shop
kubectl -n shop create secret generic shop-db-migrate \
--from-literal=url='postgres://migrator:change-me@postgres.shop.svc:5432/shop?sslmode=disable'
Use a database user that has rights to change the schema. Your application pods can keep a separate user with fewer rights.
Step 3: write the PreSync Job
Add the Job to the same Git path as the rest of the application manifests. The annotations do all the Argo CD work.
apiVersion: batch/v1
kind: Job
metadata:
name: db-migrate
namespace: shop
annotations:
argocd.argoproj.io/hook: PreSync
argocd.argoproj.io/hook-delete-policy: BeforeHookCreation,HookSucceeded
spec:
backoffLimit: 1
activeDeadlineSeconds: 900
template:
spec:
restartPolicy: Never
containers:
- name: migrate
image: registry.example.com/shop/migrations:1.8.0
args:
- "-path=/migrations"
- "-database=$(DATABASE_URL)"
- "up"
env:
- name: DATABASE_URL
valueFrom:
secretKeyRef:
name: shop-db-migrate
key: url
Kubernetes expands $(DATABASE_URL) in args from the container's environment, so the connection string never appears in the manifest. backoffLimit: 1 allows one retry for a flaky connection, and activeDeadlineSeconds makes Kubernetes fail the Job if it hangs, which in turn fails the sync instead of leaving it open.
Pick the delete policy on purpose
The argocd.argoproj.io/hook-delete-policy annotation decides when Argo CD removes the hook resource. It accepts a comma-separated list of three values. HookSucceeded deletes the hook after it succeeds, HookFailed deletes it after it fails, and BeforeHookCreation deletes an existing copy right before the new one is created. If you set no policy at all, Argo CD assumes BeforeHookCreation.
The policy in the example combines two of them. A successful Job is cleaned up, so the namespace does not fill with finished Jobs. A failed Job stays in place, so you can read its logs, and BeforeHookCreation removes it at the start of the next sync. That second part matters with a fixed name. Argo CD creates hooks with kubectl apply, so without BeforeHookCreation an existing Job with the same name would not be replaced. The alternative is metadata.generateName, which gives every run a fresh name.
Do not add ttlSecondsAfterFinished to a hook Job. Argo CD reads the Job to learn whether the phase worked, and if Kubernetes deletes it first, the sync can end up waiting for a hook that no longer exists. Let the delete policy handle cleanup.
Step 4: sync and watch the migration
Commit the Job and the new image tag together, then sync. With automated sync turned on, Argo CD picks up the commit on its own. Otherwise, start the sync from the CLI:
argocd app sync shop
While the Job runs, the sync operation stays open and the application shows Progressing. To see which phase the operation is in and which hook it is waiting for, ask for the operation state:
argocd app get shop --show-operation
The migration output lives in the Job's pod. Read it with kubectl while the Job exists:
kubectl -n shop logs job/db-migrate
In a CI pipeline, wait for the result before you mark the deploy as done. argocd app wait returns when the application is synced and healthy, or exits with an error after the timeout:
argocd app wait shop --sync --health --timeout 900
Step 5: recover from a failed migration
When the migration fails, the Job is marked failed and the sync stops in the PreSync phase. The Deployment keeps its old spec, so the pods that were already running keep serving traffic. Because of HookSucceeded, the failed Job and its pod stay in the namespace, and kubectl logs job/db-migrate shows the error.
What you do next depends on how far the migration got. If a migration fails partway, golang-migrate marks the database as dirty and refuses to run any more migrations until you fix it, printing an error such as Dirty database version 2. Fix and force version. Check by hand which statements were applied, repair the schema, and then set the recorded version to the one that matches reality:
kubectl -n shop run migrate-force --rm -it --restart=Never \
--image=registry.example.com/shop/migrations:1.8.0 \
--env="DATABASE_URL=postgres://migrator:change-me@postgres.shop.svc:5432/shop?sslmode=disable" \
-- -path=/migrations -database='$(DATABASE_URL)' force 1
The golang-migrate docs recommend wrapping a migration with several statements in a transaction (BEGIN and COMMIT on PostgreSQL). A failed statement then rolls back the whole file, and the database stays unchanged.
After the fix, push a corrected migration if one was wrong and sync again. BeforeHookCreation deletes the old failed Job, a new one starts, and the rollout continues once it succeeds. If you want Argo CD to alert someone or clean up after a failure, add a second Job with argocd.argoproj.io/hook: SyncFail. Argo CD takes no further action if that hook fails too.
Traps to know before production
Hooks run on every sync
A PreSync hook does not know whether the migration files changed. A self-heal, a manual sync from the UI or a change to an unrelated ConfigMap in the same Application all run the Job again. This is safe with golang-migrate, Flyway and similar tools, because they read their history table and do nothing when the schema is current. A hand-written SQL script that runs ALTER TABLE without checks is not safe here.
Selective syncs skip hooks
Hooks do not run during a selective sync. If someone syncs a single resource, for example with argocd app sync shop --resource apps:Deployment:web, the new Deployment goes out and the migration Job never starts. Treat selective sync as an escape hatch and run a full sync for releases that carry schema changes.
Old and new pods share the database
The rollout that follows the migration replaces pods gradually, so for a while old and new versions both read the new schema. A migration that renames or drops a column breaks the old pods during that window. Split such changes across releases: add the new column first, ship code that uses it, and drop the old column in a later release.
Long migrations hold the sync open
The sync operation stays open for as long as the hook runs. By default there is no sync timeout (controller.sync.timeout.seconds is "0"), so a stuck migration without activeDeadlineSeconds can block the application indefinitely. Terminating the operation with argocd app terminate-op shop stops the sync, but it does not stop work the hook already started in the database. Migrations that take hours, such as large backfills, belong in a dedicated controller or workflow engine that reports its own progress.
Helm charts map their own hooks
If your application is a Helm chart, Argo CD maps helm.sh/hook: pre-install and pre-upgrade to PreSync, and helm.sh/hook-weight to the sync wave. Argo CD cannot tell an install from an upgrade, so a chart with both hooks runs them in the same sync. Also, as soon as any resource in the chart carries an argocd.argoproj.io/hook annotation, Argo CD ignores all Helm hooks in that chart. Pick one style per chart rather than mixing them.