Skip to content

OpenBao: Docker secrets and a runnable example

Build AppRole → host OpenBao Agent → restricted JSON file → Docker Compose secret → Python app. The app uses the token to protect /private; /healthz returns only ok. It receives no OpenBao token, RoleID or SecretID.

Start with installation, administration and KV secrets. This guide follows OpenBao 2.7.x and assumes the existing secret/ KV v2 mount; do not enable or replace that mount again.

1. Prepare a private working copy

Use a sudo-capable non-root user on a native, local Linux Docker Engine host, with Docker access, the Compose plugin, bao, GNU timeout, Python 3 and OpenSSL. OpenBao must be initialized, unsealed and reachable over verified HTTPS. Review Docker installation/access separately; this project does not change group membership or initialize Swarm.

Docker access is root-equivalent

Membership in the Docker group or access to a rootful Docker socket can grant host-root privileges. This example runs the app as your numeric UID/GID, not root, but does not remove that administrative trust. It assumes no user-namespace remapping. Rootless Engine, Docker Desktop, remote daemons and SELinux require separate path/ownership validation; do not fix permission errors with world-readable secrets.

Download the complete example project ZIP and extract it into a private writable directory outside this repository, or copy the example from your repository clone as below. Individual downloads are also listed later.

umask 077
mkdir -p "$HOME/openbao-docker-demo"
chmod 700 "$HOME/openbao-docker-demo"
cp -R /path/to/kafana-docs-zeniscal/app/docs/1.2.Linux/How2s/OpenBao/examples/docker-demo/. \
  "$HOME/openbao-docker-demo/"
cd "$HOME/openbao-docker-demo"
mkdir -p .runtime tls
chmod 700 .runtime
install -m 0644 /path/to/trusted-public-ca.pem tls/ca.pem

The CA certificate is public, but its authenticity matters. Never copy the CA private key or server private key here. Edit agent.hcl to use your actual OpenBao hostname, matching its certificate SAN.

Never run the example in the documentation tree

Documentation builders can publish files under docs/, including live credentials. .gitignore is not a publishing filter. Work outside the source tree; keep .runtime/, local TLS material and private-key files out of Git, backups and build contexts. The app-only context and allowlist .dockerignore exclude runtime secrets from the image.

Downloadable project files

For individual web downloads, save gitignore.txt as .gitignore and app/dockerignore.txt as app/.dockerignore; these non-hidden download copies avoid site-builder exclusions. The repository copy already includes both dotfiles.

2. Store the token and configure AppRole

On this trusted demo host, authenticate as your existing named OpenBao administrator. In production, separate provisioning from runtime and deliver bootstrap credentials through an authenticated channel. Environment settings below are connection details, not credentials:

export BAO_ADDR='https://bao.lab.example:8200'
export BAO_CACERT="$PWD/tls/ca.pem"
unset BAO_TOKEN BAO_SKIP_VERIFY BAO_WRAP_TTL
bao login -no-print -method=userpass username=bao-admin
bao secrets list
bao auth list

Check that secret/ is KV v2. Enable AppRole only if approle/ does not already exist:

bao auth enable approle

Generate a random demo bearer token directly into KV, without printing it or putting its value in shell arguments/history:

openssl rand -hex 32 | bao kv put -mount=secret apps/docker-demo api_token=-
bao policy write docker-demo-read policies/docker-demo-read.hcl
bao write auth/approle/role/docker-demo \
  bind_secret_id=true \
  token_policies=docker-demo-read \
  token_type=service \
  token_num_uses=0 \
  token_ttl=10m \
  token_max_ttl=20m \
  secret_id_ttl=10m \
  secret_id_num_uses=1

This policy grants only the application's data read:

path "secret/data/apps/docker-demo" {
  capabilities = ["read"]
}

Use token_policies, not deprecated policies. Auto-auth requires token_num_uses=0 (unlimited uses within the token lifetime); it does not support use-limited tokens. The default policy remains attached for normal token self-management. The single-use SecretID limits logins, not reads made with the issued token.

Fresh demonstration names only

The KV write creates a new version and the role write creates or updates configuration. Do not overwrite an existing application's token or role without planning rotation. KV deletion or OpenBao token expiry does not rotate a credential at an external API provider.

Narrow provisioning permission

The downloadable docker-demo-provision.hcl allows only RoleID retrieval and SecretID generation for this role:

path "auth/approle/role/docker-demo/role-id" {
  capabilities = ["read"]
}
path "auth/approle/role/docker-demo/secret-id" {
  capabilities = ["update"]
}

Upload it with bao policy write docker-demo-provision policies/docker-demo-provision.hcl and attach it through the provisioner's existing human/automation auth mapping, preserving other intended policies. Do not attach it to docker-demo-read. Agent's AppRole login itself issues its policy-bearing token; no separate bao token create is needed.

3. Supply file-based bootstrap credentials

As the authorized administrator or provisioner, in the working copy:

umask 077
mkdir -p .runtime
chmod 700 .runtime
bao read -field=role_id auth/approle/role/docker-demo/role-id > .runtime/role-id
bao write -field=secret_id -f auth/approle/role/docker-demo/secret-id > .runtime/secret-id
chmod 600 .runtime/role-id .runtime/secret-id

Generate a new SecretID before every Agent run. It expires after 10 minutes, is usable for one login and is deleted from disk by Agent after reading. Deleting that input file is not server-side revocation. The RoleID file remains; neither file goes into the container.

Optional: wrap SecretID delivery

Instead of the plaintext SecretID command, redirect a five-minute, single-use wrapping token:

bao write -wrap-ttl=5m -field=wrapping_token \
  -f auth/approle/role/docker-demo/secret-id > .runtime/secret-id

Add the following inside the AppRole method's config map in agent.hcl:

secret_id_response_wrapping_path = "auth/approle/role/docker-demo/secret-id"

Agent checks that creation path and unwraps the response. Do not mix wrapped/plain input with the wrong config. This wraps SecretID delivery, not the login response: setting wrap_ttl on the auto-auth method is different and prevents normal Agent token management.

4. Understand the one-shot Agent and Compose configuration

The downloadable Agent config starts with:

exit_after_auth = true
vault {
  address = "https://bao.lab.example:8200"
  ca_cert = "./tls/ca.pem"
  retry { num_retries = 3 }
}
auto_auth {
  method "approle" {
    mount_path = "auth/approle"
    exit_on_err = true
    config = {
      role_id_file_path                  = "./.runtime/role-id"
      secret_id_file_path                = "./.runtime/secret-id"
      remove_secret_id_file_after_reading = true
    }
  }
}

The stanza remains named vault in OpenBao. Exported BAO_ADDR/BAO_CACERT override those settings; keep them consistent. There is no token sink: templating uses the token in memory, and the app never receives it. exit_on_err makes login errors fatal; template failures are controlled separately:

template_config { exit_on_retry_failure = true }
template {
  source               = "./templates/app.json.ctmpl"
  destination          = "./.runtime/app.json"
  perms                = "0600"
  backup               = false
  create_dest_dirs     = false
  error_on_missing_key = true
}

backup=false avoids a plaintext .bak; explicit permissions avoid the template's 0644 new-file default. Pre-create .runtime/ with mode 0700. The template uses the KV v2 API path and escaped JSON:

{{- with secret "secret/data/apps/docker-demo" -}}
{"api_token": {{ .Data.data.api_token | toJSON }}}
{{- end -}}

The CLI's logical path is apps/docker-demo; policy/template API paths include secret/data/. Values are under .Data.data, not KV v1's .Data. secret/config is the KV engine's configuration endpoint, not this application's secret.

Compose grants just this file to the app:

services:
  app:
    build: ./app
    user: "${APP_UID:?Run through run.sh}:${APP_GID:?Run through run.sh}"
    ports:
      - "127.0.0.1:8080:8080"
    secrets:
      - app_config
secrets:
  app_config:
    file: ./.runtime/app.json

The full file adds a read-only root filesystem, dropped capabilities and a healthcheck. Local Compose file secrets are read-only single-file bind mounts. Their host ownership/mode matters: Compose silently ignores secret uid, gid and mode for file: sources. The matching non-root host UID reads the 0600 source at /run/secrets/app_config. Pin reviewed base-image digests for production; tags are mutable.

5. Start and verify without exposing the token

Review the downloaded files, then run as your regular user, not sudo:

sh ./run.sh
export APP_UID="$(id -u)" APP_GID="$(id -g)"
docker compose ps
curl --fail http://127.0.0.1:8080/healthz
python3 -B ./verify.py

run.sh uses set -eu, rejects root, checks inputs, exports only numeric APP_UID/APP_GID, and does not source .env. Its startup gate is:

timeout --kill-after=5s 60s bao agent -config=agent.hcl
test -s .runtime/app.json
docker compose config -q
docker compose up --build -d --force-recreate app

With templates configured, exit_after_auth=true waits for their initial successful render, including unchanged content, before successful exit. After exit there is no polling, token renewal or lease renewal. On timeout/login/template failure, set -e prevents deployment even if an old file exists. An already running old container is not stopped by this gate; decide explicitly whether stale credentials should fail closed in your deployment.

The verifier checks fixed health output, missing/wrong bearer rejection and valid bearer acceptance. It reads the host JSON and constructs the request header in memory, printing only test outcomes. If startup is still in progress, wait for the healthcheck and retry. The app loads the token once, compares bytes with hmac.compare_digest, and suppresses HTTP access logging.

Illustrative local HTTP, not a production public service

Loopback publication limits host exposure; other containers on its network can still reach it. Bearer credentials traverse local HTTP without TLS. Do not publish it publicly or send real credentials through it. Use a production server, validated HTTPS, rate limits and suitable authentication in real applications. Host root and Docker administrators can read secrets; files are not protection from the authorized application itself.

Never use set -x, cat the secret, embed it in YAML/source, or pass it through .env, BAO_TOKEN, curl -H "...$(cat ...)" or other expanded command arguments. Hidden prompts, protected files and stdin avoid those exposures; protect token-helper storage and do not record login terminals.

6. Rotate and clean up

To rotate this demo application's own token, update KV using the OpenSSL pipeline from section 2, issue a fresh SecretID using section 3, then rerun sh ./run.sh and python3 -B ./verify.py. Existing clients must obtain the new token through a secure channel.

A rendered file is not automatic hot reload

Agent replaces templates atomically; a Linux single-file bind mount can retain the old inode. Force-recreate containers after rendering; do not rely on docker compose restart or rereading the old mount. The app also caches its token. For continuous renewal/reload, use a supervised daemon Agent, a narrowly scoped read-only directory mount and application reload/reconnection logic instead of promising live Compose secret updates.

A daemon Agent renews until token renewal fails or maximum TTL is reached, then reauthenticates. Cached SecretIDs can expire or exhaust their uses; a trusted provisioner must supply replacements. KV v2 is non-leased and normally polled every five minutes (static_secret_render_interval). Dynamic credentials have lease-specific renewal/refetch rules: this one-shot demo is not a continuously renewed database-credential design.

Stop/remove the app before removing its file, from the same working copy:

export APP_UID="$(id -u)" APP_GID="$(id -g)"
docker compose down
rm -f .runtime/app.json .runtime/role-id .runtime/secret-id
rmdir .runtime

Compose does not delete host secret files. Unlinking files is not guaranteed secure erasure on SSDs, snapshots or backups; use a restricted RAM-backed runtime directory where appropriate. The unsunk AppRole token expires without renewal; deleting a role/SecretID does not revoke already issued tokens or erase rendered values. Explicit revocation, when required, needs a separately managed token accessor.

For dedicated demo resources only, an administrator can run bao delete auth/approle/role/docker-demo, bao policy delete docker-demo-read, and bao policy delete docker-demo-provision (if created). Remove its provisioning auth mapping first. bao kv metadata delete -mount=secret apps/docker-demo irreversibly deletes all demo versions; do not disable the shared KV or AppRole mounts.

7. Docker Compose versus Docker Swarm secrets

These are different lifecycles despite the same /run/secrets/ convention:

Linux behavior Local docker compose up with file: Docker Swarm services
Delivery Read-only host-file bind mount Decrypted in-memory mount for authorized tasks
At rest Host source is plaintext unless separately protected Managed secret encrypted in Raft; any source file still needs cleanup
Permissions Host UID/GID/mode; secret overrides ignored Linux task secret UID/GID/mode supported
Rotation Render then recreate; app reload is your responsibility Immutable objects: create versioned secret, update service, remove old
Stop/remove Unmount does not delete host file Task shutdown unmounts/flushes decrypted secret; managed object persists
Commands No Swarm secret object from ordinary Compose docker secret and docker service on an existing Swarm

A Swarm handoff copies an already rendered snapshot into a separate managed secret. On an existing Swarm manager, after publishing the app image to a registry accessible to workers, substitute that image below. This example does not publish the HTTP port or initialize a cluster:

docker secret create docker-demo-v1 .runtime/app.json
docker service create --name docker-demo --user 10001:10001 \
  --secret source=docker-demo-v1,target=app_config,uid=10001,gid=10001,mode=0400 \
  registry.example.com/docker-demo:reviewed
# After rendering the replacement with a fresh SecretID and one-shot Agent:
docker secret create docker-demo-v2 .runtime/app.json
docker service update --secret-rm docker-demo-v1 \
  --secret-add source=docker-demo-v2,target=app_config,uid=10001,gid=10001,mode=0400 docker-demo
docker service ps docker-demo
# After confirming the rollout has finished:
docker secret rm docker-demo-v1
docker service rm docker-demo
docker secret rm docker-demo-v2

Swarm cannot modify a secret object or remove one still referenced by a service. Updating the service replaces tasks; do not remove the service until you want teardown. Removing a Docker secret does not revoke the credential upstream. Use docker stack deploy for a Swarm Compose-file deployment; local Compose does not become Swarm secret delivery through external: true. These guarantees describe Linux; Windows Swarm secret storage differs.

Official references