> For the complete documentation index, see [llms.txt](https://spice.docs.medtroniclabs.org/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/docker-compose.md).

# Docker Compose Install

This page describes how to run the whole SPICE backend on one machine with Docker Compose. Use it for **local development, evaluation, demos and small installs**. For production, read [Before you expose it](#before-you-expose-it) and see the other pages in this section.

> **Warning: the Compose setup is not production-ready.** Out of the box it publishes every internal port on the host, serves plain HTTP, runs Redis without a password, relies on example credentials from the template, and runs everything on a single machine with no redundancy. Do not expose it to the internet or put real patient data in it until you have completed the checklist at the end of this page.

## What you get

One command starts these containers on a private Docker network:

| Container             | Component                                       | Host port                                          |
| --------------------- | ----------------------------------------------- | -------------------------------------------------- |
| `nginx`               | Reverse proxy / API gateway                     | 80                                                 |
| `authservice`         | Authentication                                  | 8089                                               |
| `userservice`         | Users, organisations, core database migrations  | 8085                                               |
| `adminservice`        | Administrative services                         | 8086                                               |
| `spiceservice`        | Core clinical and programme services            | 8087                                               |
| `offlineservice`      | Mobile data sync                                | 8093                                               |
| `notificationservice` | E-mail and SMS                                  | 8084                                               |
| `fhirmapper`          | FHIR mapping                                    | 8092                                               |
| `fhirserver`          | HAPI FHIR server                                | `FHIR_SERVER_PORT` (8091 in the template examples) |
| `cqlservice`          | Clinical rules (CQL)                            | 8094                                               |
| `cfrservice`          | Facility registry and reporting APIs            | 8050                                               |
| `postgres`            | PostgreSQL (core, FHIR and reporting databases) | 5432                                               |
| `redis`               | Cache                                           | 6379                                               |
| `rabbitmq`            | Message queue (management UI on 15672)          | 5672                                               |

The web applications and the Android app are **not** part of the Compose file. You run or build them separately (below).

## Prerequisites

* A machine with plenty of memory. The FHIR server (default memory limit 4 GB) and the FHIR mapper (3 GB) are the largest containers, and there are fourteen containers in total, so allocate well above those two figures to Docker.
* Docker Engine and Docker Compose v2 (`docker compose version` must work).
* JDK 25 and Apache Maven 3.8.3 or newer, to build the backend. The Dockerfiles copy pre-built jar files, so the Java build happens on your machine before the image build.
* Node.js 22 or newer, to run the web application.
* Git.

Versions are explained in [Components & Requirements](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/components-and-requirements.md).

## 1. Get the source

Create one working directory and clone each repository into it as a sibling, so the layout looks like this:

```
spice/
├── common-service/
├── user-service/            # contains auth-service, user-service and the Compose files
├── spice-service/           # contains admin-service, spice-service, cql-service
├── notification-service/
├── offline-service/
├── fhir-mapper/
├── fhir-server/
├── cfr-service/
├── spice_web/
└── report_web/              # optional
```

```bash
mkdir spice && cd spice
git clone <repository-url>/common-service.git
git clone <repository-url>/user-service.git
# ...repeat for the other repositories listed above
```

The Compose file and its helper files are in the `user-service` repository.

## 2. Configure

```bash
cd user-service
cp env.example .env
```

Edit `.env`. It is read by Docker Compose from the same directory as `docker-compose.yml`. The template has many variables, most of them optional features. These are the ones to set for a first start:

```bash
# Absolute paths to the cloned repositories (required for the image builds)
PROJECT_PATH=/path/to/spice/user-service
NOTIFICATION_PROJECT_PATH=/path/to/spice
CFR_PROJECT_PATH=/path/to/spice
OFFLINE_PROJECT_PATH=/path/to/spice
SPICE_PROJECT_PATH=/path/to/spice/spice-service
FHIR_PROJECT_PATH=/path/to/spice/fhir-mapper
FHIR_SERVER_PROJECT_PATH=/path/to/spice/fhir-server

# Databases (host name is the Compose service name "postgres")
DATABASE_URL=jdbc:postgresql://postgres:5432/spice_core
DATABASE_NAME=spice_core
DATABASE_USERNAME=<db-user>
DATABASE_PASSWORD=<change-me>
FHIR_DATABASE_NAME=spice_fhir
FHIR_DATASOURCE_URL=jdbc:postgresql://postgres:5432/spice_fhir
FHIR_DATASOURCE_USERNAME=<db-user>
FHIR_DATASOURCE_PASSWORD=<change-me>
REPORT_DATABASE_NAME=spice_report
REPORT_DB_URL=jdbc:postgresql://postgres:5432/spice_report
REPORT_DB_USERNAME=<db-user>
REPORT_DB_PASSWORD=<change-me>
DB_MAX_POOL_SIZE=10

# Cache and queue
REDIS_HOST=redis
REDIS_PORT=6379
IS_RABBITMQ_SQS_ENABLED=true
IS_AWS_SQS_ENABLED=false
RABBIT_MQ_HOST=rabbitmq
RABBIT_MQ_PORT=5672
RABBIT_MQ_USERNAME=<mq-user>
RABBIT_MQ_PASSWORD=<change-me>

# Service-to-service URLs (Compose service names and container ports)
AUTH_SERVICE=http://authservice:8089
USER_SERVICE=http://userservice:8085
ADMIN_SERVICE=http://adminservice:8086
SPICE_SERVICE=http://spiceservice:8087
OFFLINE_SERVICE=http://offlineservice:8093
NOTIFICATION_SERVICE=http://notificationservice:8084
FHIR_SERVICE=http://fhirmapper:8092
CQL_SERVICE=http://cqlservice:8094
CFR_SERVICE=http://cfrservice:8050

# FHIR server
FHIR_SERVER_PORT=8091
HAPI_SERVER_URL=http://fhirserver:8091/fhir/
HAPI_IDENTIFIER_URL=https://<your-domain>/
APP_VALIDATE_TOKEN_API=http://authservice:8089/authenticate
FHIR_SERVER_AUTH_ENABLED=true

# Browser access
DOMAIN_NAME=localhost
ALLOWED_ORIGINS=http://localhost:3000,http://localhost:3001
AUTH_TOKEN_TIME_LIMIT_IN_MINUTES=240

# Storage for sync files: use the local filesystem for a local install
OFFLINE_STORAGE_PROVIDER=local
# The spice-service container bind-mounts this path; it must be an existing file
GOOGLE_APPLICATION_CREDENTIALS=/path/to/an/existing/empty-file

# Scheduler lock durations (no defaults)
SHEDLOCK_EMAIL_START=PT30S
SHEDLOCK_EMAIL_STOP=PT02M
SHEDLOCK_SMS_START=PT30S
SHEDLOCK_SMS_STOP=PT02M
SHEDLOCK_OUTBOUND_START=PT24H
SHEDLOCK_OUTBOUND_STOP=PT25H

# Internal service account and internal-identity keys: see Configuration
JOB_USER_NAME=<job-user>
JOB_USER_PASSWORD=<change-me>
INTERNAL_ASSERTION_PRIVATE_KEY=<generated>
INTERNAL_ASSERTION_PUBLIC_KEY=<generated>
```

Notes:

* Use your own values for every `<change-me>`. Do not copy passwords from examples.
* Generate the two `INTERNAL_ASSERTION_*` keys as shown in [Configuration](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/configuration.md#authentication-and-sessions).
* Variables you do not use (SMS gateways, DHIS-style integrations, object storage buckets, and so on) can stay blank. See [Configuration](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/configuration.md) for what each group does.
* Create the log directory that the containers mount: `mkdir -p log` (inside `user-service`).

## 3. Build the backend

Install the shared library first, then build each service. `-DskipTests` keeps the build fast; run the tests separately if you need them.

```bash
cd /path/to/spice

(cd common-service && mvn -B -DskipTests clean install)

for svc in user-service spice-service notification-service offline-service fhir-mapper cfr-service; do
  (cd "$svc" && mvn -B -DskipTests clean package)
done

(cd fhir-server && mvn -B -DskipTests clean package)   # produces target/ROOT.war
```

`user-service` builds both `auth-service` and `user-service`; `spice-service` builds `admin-service`, `spice-service` and `cql-service`. The Docker image build step expects the resulting `target/` folders to exist.

## 4. Build the images and start everything

From the `user-service` directory:

```bash
docker compose up -d --build
```

This builds one image per service and starts all containers. The first start takes a while: PostgreSQL creates the three databases, `userservice` applies the core migrations and `fhirserver` applies its own. Services that start before the migrations finish may restart a few times (`restart: always`) until the schema is ready.

The repository also contains `build-local.sh`, a wrapper that stamps each image with the git commit of its source repository and then runs the same Compose commands (`./build-local.sh`, `./build-local.sh build <service>`, `./build-local.sh up <service>`; any other Compose subcommand is passed through). It needs the seven `*_PROJECT_PATH` variables, either exported in your shell or defined in a `.env` file one directory above the script. Using `docker compose` directly, as above, gives the same result without the commit labels.

## 5. Databases and initial data

* **Databases.** On first start of an empty `postgres` volume, `docker-entrypoint-initdb.sh` creates the core, FHIR and reporting databases named by `DATABASE_NAME`, `FHIR_DATABASE_NAME` and `REPORT_DATABASE_NAME`. It does not run again once the volume exists.
* **Core and FHIR schemas** are created by Flyway migrations: `user-service` migrates the core database and `fhir-server` migrates the FHIR database. You do not run these by hand.
* **Reporting schemas (optional).** If you want the reporting database populated, copy the two schema files from the reporting ETL component's `sql` directory into `user-service/initdb-seed/` (copy, do not symlink) **before the first start**:

  ```bash
  cp /path/to/report-etl/sql/core-schema.sql   initdb-seed/report-core-schema.sql
  cp /path/to/report-etl/sql/report-schema.sql initdb-seed/report-report-schema.sql
  ```

  They load only into an empty database. See `initdb-seed/README.md` for details and for optional starter dumps.
* **Reference data and first administrator.** The migrations seed roles, menus and permissions, and create a bootstrap administrator account and an internal service account so the first login is possible. Use [Data Import & Migration](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/data-import-and-migration.md) to load your administrative hierarchy, facilities and users.

## 6. Check health

```bash
docker compose ps                        # all containers should be "running"; postgres "healthy"

for svc in auth-service user-service admin-service spice-service offline-service \
           notification-service fhir-mapper cql-service cfr-service fhir-server; do
  printf '%-22s' "$svc"; curl -s -o /dev/null -w '%{http_code}\n' "http://localhost/$svc/actuator/health"
done
```

Each service exposes unauthenticated `/actuator/health` and `/actuator/info` endpoints through the proxy. `info` returns the commit the image was built from. A `200` means the service is up. The FHIR server can take several minutes on first start.

## 7. Run the web application

The web application runs on your machine and talks to the Compose stack.

```bash
cd /path/to/spice/spice_web
cp env.example .env
# edit .env: REACT_APP_BASE_URL=http://localhost  (the proxy on port 80)
#            REACT_APP_PASSWORD_HASH_KEY=<your-key>
#            REACT_APP_CRYPTR_SECRET_KEY=<your-key>
npm install
npm start
```

Open `http://localhost:3000/`. When the base URL is `http://localhost`, the dev server forwards each service prefix straight to the published service ports. `ALLOWED_ORIGINS` in the backend `.env` must include the address you browse from (`http://localhost:3000` by default).

To produce a static build for any web server, run `npm run build`; the output is in `build/`. Set `REACT_APP_BASE_URL` to the public API URL before building, since the value is compiled in. See [Web Applications](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/admin-portal.md).

The optional reporting web application (`report_web`) is started the same way (`npm install`, then `PORT=3001 npm start`, so it does not collide with the first app). It loads its runtime settings from a `config.json` file served next to the app (the format is in `report_web/deploy/config.schema.json`); create `public/config.json` for local use. See [Configuration](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/configuration.md).

## 8. Point the mobile app at the stack

The Android app has its server URLs compiled in. To use your Compose stack:

1. In the Android project, set the API base URL, admin base URL, salt and database-encryption key properties for the flavor you build in `environment.properties`. See [Mobile App](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/android.md) for the property names.
2. Use the proxy address as the API base URL: `http://<your-machine-ip>/` for a physical device on the same network, or `http://10.0.2.2/` from the Android emulator (which maps to the host machine).
3. Build and install: `./gradlew :app:assembleDevDebug` (from the Android project directory), then install the APK.

The app permits plain HTTP so this works locally. A production build must use HTTPS.

## Common operations

Run these from the `user-service` directory.

| Task                                                   | Command                                                                                                      |
| ------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------ |
| Follow logs of one service                             | `docker compose logs -f userservice`                                                                         |
| Show recent logs of everything                         | `docker compose logs --tail=100`                                                                             |
| Restart one service                                    | `docker compose restart spiceservice`                                                                        |
| Rebuild one service after a code change                | `(cd ../spice-service && mvn -B -DskipTests clean package)` then `docker compose up -d --build spiceservice` |
| Stop the stack, keep data                              | `docker compose down`                                                                                        |
| Start it again                                         | `docker compose up -d`                                                                                       |
| Stop and **delete all data** (databases, cache, queue) | `docker compose down -v`                                                                                     |
| Back up a database                                     | `docker compose exec -T postgres pg_dump -U <db-user> <database-name> > backup.sql`                          |
| Open a SQL shell                                       | `docker compose exec postgres psql -U <db-user> <database-name>`                                             |

Service names are the container names in the table above (`userservice`, `fhirserver`, and so on).

If you change `common-service`, rebuild and reinstall it and then rebuild **all** services, because each service bundles its own copy of the library. If you change only one service, rebuild just that one.

### Reset to a clean state

```bash
docker compose down -v
docker compose up -d --build
```

This removes the PostgreSQL, Redis and RabbitMQ volumes, so the databases are recreated and the migrations run again. Delete the `log/` directory contents too if you want clean logs.

## Troubleshooting

| Symptom                                                                  | Likely cause and fix                                                                                                                                                                   |
| ------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Build fails with `path "/cfr-service" not found` (or similar)            | One of the `*_PROJECT_PATH` variables in `.env` is blank or wrong. Use absolute paths.                                                                                                 |
| Image build fails at the step that adds `target/*.jar` (or `ROOT.war`)   | The Maven build for that service was not run, or failed. Repeat step 3.                                                                                                                |
| `docker compose up` fails mounting a credentials file for `spiceservice` | `GOOGLE_APPLICATION_CREDENTIALS` is empty. Set it to the path of an existing file.                                                                                                     |
| `nginx` exits with `host not found in upstream`                          | A backend container was not created. Run `docker compose ps -a`, find the failed service and read its logs.                                                                            |
| Service restarts repeatedly right after the first start                  | Normal for a short time while `userservice` and `fhirserver` finish their migrations. If it persists, read the logs: usually a wrong database URL, user or password.                   |
| `502 Bad Gateway` on login                                               | A service is still starting, or you replaced the proxy configuration. The shipped `nginx.conf` enlarges buffers because login responses carry large headers.                           |
| Browser shows CORS errors                                                | The address you browse from is missing from `ALLOWED_ORIGINS`. Add it and restart the services.                                                                                        |
| `bind: address already in use`                                           | Another program uses a published port (80, 5432, 6379, 5672, 8xxx). Stop it, or change the host side of the port mapping.                                                              |
| Database or schema changes in `.env` have no effect                      | The init scripts run only against an empty volume. Reset with `docker compose down -v`.                                                                                                |
| Containers killed or very slow, FHIR server out of memory                | Not enough memory for Docker. Raise the Docker memory allocation, or the limits `FHIR_SERVER_MEM_LIMIT` and `FHIR_MAPPER_MEM_LIMIT`.                                                   |
| Sync uploads time out                                                    | Large uploads need long timeouts. Keep the proxy limits (150 MB body, 300 s) if you put another proxy in front.                                                                        |
| Mobile app cannot connect                                                | Wrong base URL for the device (use the machine's LAN IP or `10.0.2.2`), firewall blocking port 80, or an app build made before you changed the URL. Rebuild the app after changing it. |

## Before you expose it

The Compose defaults are for non-production use. Before the stack is reachable by anyone other than you, or holds real data:

* **Passwords and keys.** Replace every example or default credential: database, message queue, internal service account, internal-identity keys, web password-hash and encryption keys. Change the bootstrap administrator credentials. Keep `.env` out of version control and restrict file permissions.
* **Ports.** Remove the `ports:` mappings from every container except `nginx` (edit the file, or use an override file with `ports: !reset []`, which needs Compose 2.24 or newer). PostgreSQL, Redis, RabbitMQ (including its management UI on 15672) and the services must not be reachable from outside the host.
* **TLS.** The shipped proxy configuration listens on HTTP port 80 only. Terminate HTTPS in front of it with a trusted certificate, or add TLS to the proxy. Use `https://` URLs in the web build, `ALLOWED_ORIGINS` and the mobile build.
* **Redis.** It runs without a password; keep it private or enable authentication.
* **Images.** The Compose file references the `nginx:1.13-alpine` image and unpinned `redis`, `rabbitmq` and `postgres` tags. Move to supported, pinned versions.
* **Debug features.** Set `SWAGGER_ENABLED=false`. Restrict `HAPI_FHIR_CORS_ALLOWED_ORIGIN` to your own origins.
* **Volumes and backups.** Data lives in Docker named volumes on one machine. Schedule `pg_dump` backups to storage elsewhere and test a restore. Mount the `log/` directory on persistent storage or ship logs off the host, and rotate them.
* **Availability.** One host is a single point of failure. For production use a container orchestrator, managed or replicated PostgreSQL, a message queue and cache with persistence, and real object storage. See [Components & Requirements](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/components-and-requirements.md) and [Sizing & Operations](https://spice.docs.medtroniclabs.org/deploy/deployment-guide/sizing-and-operations.md).
