SPRING SECURITY / 07

Full deployment with Docker

Deploy MySQL, Spring Boot and React with Nginx using one command from the root.

One Compose file for the entire application

The file compose.yml at the root builds and runs MySQL, Spring Boot and React served by Nginx. Start everything with docker compose up -d --build --wait and open localhost:8088.

The Compose project is named security-lab-full and stores MySQL in volume security-lab-full_mysql_data. Stopping, rebuilding or recreating containers preserves data as long as you retain this volume and project name.

Browser :8088→Nginx frontend :8081→ /apiSpring backend :7070→MySQL :3306

Nginx serves React static files and preserves the /api prefix when proxying requests to Spring. The browser sees one origin; backend and mysql are internal Compose DNS names. MySQL and Spring are accessible only within Docker. The browser accesses the application and /api through localhost:8088.

1. Included files

FilePurpose
compose.ymlFull deployment from the root: services, network, variables, healthchecks, restart and volume.
backend.DockerfileJava 21 build with Maven, tests and JAR execution as an unprivileged user.
frontend.DockerfileBuild with Node 22 and pnpm 10.33.4; final Nginx image.
nginx.conf/api proxy, React route fallback and Nginx liveness check.

Dockerfiles use the root as context but copy only specific files. The file .dockerignore excludes .env, node_modules, dist, target and other local files from the build context. Dockerfiles copy only required files. Maven uses a dependency cache during the build and runs tests before creating the JAR. Docker Compose coordinates services; the backend has no Spring container-startup integration. The final Java image contains only the runtime and JAR, without Maven. The frontend image contains only Nginx and the build, without Node or pnpm.

2. Prepare secrets and the initial administrator

Prepare .env as described in Configuration: OpenSSL for JWT_SECRET and your own database passwords. This Compose file explicitly uses required variables and replaces DB_URL with the correct internal address. MySQL publishes no host port. Origins use DOCKER_FRONTEND_URL; development FRONTEND_URL is not reused.

For a new database requiring an initial ADMIN account, use the existing initialiser: set DEMO_ENABLED=true and strong DEMO_ADMIN_PASSWORD and DEMO_USER_PASSWORD values before first startup. It creates admin@example.com and user@example.com. After confirming access, set DEMO_ENABLED=false and recreate backend. This does not delete created accounts. If disabled from the start, public registration creates only USER accounts and there is no initial ADMIN.

Full-deployment variables

VariableDefault value / configurationEffect
DB_USER / DB_PASSWORD / MYSQL_ROOT_PASSWORDUser security_app; set your own passwords.Initialisation of the MySQL volume and backend connection using the application user.
JWT_SECRET / JWT_EXPIRATION_SECONDSYour own secret of at least 32 UTF-8 bytes; lifetime 900 seconds.JWT signing and expiration.
HTTP_BIND127.0.0.1Host interface on which Nginx is published.
HTTP_PORT8088Browser access port.
DOCKER_FRONTEND_URLhttp://localhost:8088,http://127.0.0.1:8088Deployment CORS origins. Adjust them when changing port or using a domain.
DEMO_ENABLED / DEMO_ADMIN_PASSWORD / DEMO_USER_PASSWORDInitialiser disabled by default; define passwords if enabling it.Creates missing initial accounts; does not change existing accounts.

DB_URL is fixed in the full Compose file to jdbc:mysql://mysql:3306/security_lab?serverTimezone=UTC. The file does not use DB_PORT. Nginx uses /api and the frontend is built with VITE_API_URL=/api; it need not know the backend's internal address.

3. Build and start from the root

shell
# Comprueba que Docker esté iniciado y que .env esté preparado.
docker compose version

# Valida sin imprimir el contenido expandido de los secretos.
docker compose config --quiet

# Construye, ejecuta las pruebas Java y espera los healthchecks.
docker compose up -d --build --wait

docker compose ps

Open http://localhost:8088. The first build downloads images and dependencies and requires Internet. You do not need Java, Maven, Node or pnpm installed on the host in this mode: builds run inside Docker.

MySQL must answer SELECT 1 before backend starts. Backend must return 401 from /api/me without credentials before Nginx starts. Nginx checks its own /healthz route. No Actuator was added: the expected 401 proves Spring's HTTP chain responds, not continuous exhaustive database health. Compose waits for service_healthy dependencies: official startup order.

4. Verify the complete application

shell
# Debe devolver HTML y código 200.
curl -I http://localhost:8088/

# Debe devolver el JSON 401 de Spring, no index.html.
curl -i http://localhost:8088/api/me

# Una ruta de React también debe servir el documento inicial.
curl -I http://localhost:8088/usuarios

# Revisa los mensajes de arranque si falla.
docker compose logs --tail=100 backend frontend mysql

Then sign in, view your profile and, as ADMIN, create a test account. For API examples, change the base URL http://localhost:7070 to http://localhost:8088. /usuarios returns the React document, but its guard and Spring still require the appropriate permissions.

5. Update and administer

shell
# Reconstruir tras cambios de código; conserva el volumen.
docker compose up -d --build --wait

# Aplicar cambios de variables de backend (por ejemplo DEMO_ENABLED=false).
docker compose up -d --force-recreate backend

# Detener sin eliminar datos.
docker compose stop

# Eliminar contenedores y red, conservando el volumen.
docker compose down

Back up and restore the database

From the root, with services running, create a logical dump. The file contains personal data and hashes; store it outside the repository with restricted access.

shell
# La expansión de estas variables ocurre dentro del contenedor.
# Usa una ruta privada propia para el archivo de copia.
docker compose exec -T mysql   sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysqldump --no-tablespaces --single-transaction -u "$MYSQL_USER" "$MYSQL_DATABASE"'   > /tmp/security-lab-backup.sql

# Restaurar en una BD de destino preparada. Revisa el destino antes:
# puede sobrescribir tablas existentes.
docker compose exec -T mysql   sh -c 'MYSQL_PWD="$MYSQL_PASSWORD" exec mysql -u "$MYSQL_USER" "$MYSQL_DATABASE"'   < /tmp/security-lab-backup.sql

6. Publish on a server

Copy the project, compose.yml and Dockerfiles to a server with Docker Compose; create a private .env there with new secrets. The HTTP port binds only to 127.0.0.1 by default. For production, put a domain/TLS proxy in front, forwarding to that local port. Set DOCKER_FRONTEND_URL to the public origin, for example https://lab.tudominio.com. If the proxy is in another container, give it network access to frontend or use a reachable host address.

HTTP_BIND=0.0.0.0 exposes the port on external interfaces; use it only when required by the architecture and firewall. HTTP_PORT selects another published port. Changing it also requires adjusting DOCKER_FRONTEND_URL when the browser origin changes. Keep the database private, restrict server access and prepare verified backups and restores.

Example images use maintained version tags, which can change. For reproducible deployment, pin verified versions or digests and define an update process. Before accepting real accounts, complete the pending security features described in Security.

Complete deployment configuration

View Compose
yaml
# Aplicación completa. Desde la raíz:
# docker compose up -d --build --wait
name: security-lab-full
services:
  mysql:
    image: mysql:8.4
    environment:
      MYSQL_DATABASE: security_lab
      MYSQL_USER: ${DB_USER:-security_app}
      MYSQL_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD en .env}
      MYSQL_ROOT_PASSWORD: ${MYSQL_ROOT_PASSWORD:?Define MYSQL_ROOT_PASSWORD en .env}
    volumes:
      - mysql_data:/var/lib/mysql
    healthcheck:
      test: ["CMD-SHELL", "MYSQL_PWD=$$MYSQL_PASSWORD mysql -h 127.0.0.1 -u $$MYSQL_USER -D security_lab -e 'SELECT 1'"]
      interval: 5s
      timeout: 5s
      retries: 30
    restart: unless-stopped

  backend:
    build:
      context: .
      dockerfile: docker/backend.Dockerfile
    environment:
      SPRING_DOCKER_COMPOSE_ENABLED: "false"
      DB_URL: jdbc:mysql://mysql:3306/security_lab?serverTimezone=UTC
      DB_USER: ${DB_USER:-security_app}
      DB_PASSWORD: ${DB_PASSWORD:?Define DB_PASSWORD en .env}
      JWT_SECRET: ${JWT_SECRET:?Define JWT_SECRET en .env}
      JWT_EXPIRATION_SECONDS: ${JWT_EXPIRATION_SECONDS:-900}
      FRONTEND_URL: ${DOCKER_FRONTEND_URL:-http://localhost:8088,http://127.0.0.1:8088}
      DEMO_ENABLED: ${DEMO_ENABLED:-false}
      DEMO_ADMIN_PASSWORD: ${DEMO_ADMIN_PASSWORD:-}
      DEMO_USER_PASSWORD: ${DEMO_USER_PASSWORD:-}
    depends_on:
      mysql:
        condition: service_healthy
    healthcheck:
      # No hay Actuator: la ruta protegida sin token debe responder 401.
      test: ["CMD-SHELL", "wget -S -O /dev/null http://127.0.0.1:7070/api/me 2>&1 | grep -q 'HTTP/1.1 401'"]
      interval: 10s
      timeout: 5s
      retries: 30
      start_period: 30s
    restart: unless-stopped

  frontend:
    build:
      context: .
      dockerfile: docker/frontend.Dockerfile
    ports:
      - "${HTTP_BIND:-127.0.0.1}:${HTTP_PORT:-8088}:8081"
    depends_on:
      backend:
        condition: service_healthy
    healthcheck:
      test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8081/healthz"]
      interval: 10s
      timeout: 5s
      retries: 10
    restart: unless-stopped
volumes:
  mysql_data:
View backend Dockerfile
dockerfile
FROM maven:3.9-eclipse-temurin-21 AS build
WORKDIR /build
COPY backend/pom.xml ./pom.xml
COPY backend/src ./src
RUN --mount=type=cache,target=/root/.m2 mvn -B -ntp clean verify

FROM eclipse-temurin:21-jre-alpine
RUN addgroup -S spring && adduser -S spring -G spring
WORKDIR /app
COPY --from=build --chown=spring:spring /build/target/security-lab-1.0.0.jar app.jar
USER spring
EXPOSE 7070
ENTRYPOINT ["java", "-jar", "/app/app.jar"]
View frontend Dockerfile
dockerfile
FROM node:22-alpine AS build
WORKDIR /build
RUN corepack enable && corepack prepare pnpm@10.33.4 --activate
COPY frontend/package.json frontend/pnpm-lock.yaml ./
RUN pnpm install --frozen-lockfile
COPY frontend/index.html frontend/vite.config.js ./
COPY frontend/src ./src
ENV VITE_API_URL=/api
RUN pnpm build

FROM nginx:stable-alpine
COPY docker/nginx.conf /etc/nginx/conf.d/default.conf
COPY --from=build /build/dist /usr/share/nginx/html
EXPOSE 8081
View Nginx
nginx
server {
    listen 8081;
    server_name _;
    root /usr/share/nginx/html;
    index index.html;

    location = /healthz {
        access_log off;
        default_type text/plain;
        return 200 'ok';
    }

    location /api/ {
        # Sin barra final: conserva /api al reenviar a Spring.
        proxy_pass http://backend:7070;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
    }

    location / {
        # Rutas React como /usuarios también deben funcionar al recargar.
        try_files $uri $uri/ /index.html;
    }
}

Common problems

SymptomWhat to check
MySQL unhealthyLogs, existing-volume credentials and DB_USER. Wait for initial setup.
Spring cannot connectInside Docker use mysql:3306, never localhost:3307. Check DB_PASSWORD and migrations.
JWT_SECRET needs 32 bytesGenerate openssl rand -hex 32, update .env and recreate backend.
Flyway checksum mismatchDo not edit applied migrations; restore their content and create a new version.
Nginx 502Backend must be available at backend:7070. If recreation changed its IP, restart frontend to refresh Nginx name resolution.
404 when reloading /usuariosCheck try_files with an /index.html fallback in Nginx.
The API returns HTMLCheck location /api/ and that proxy_pass preserves /api.
CORS errorExact origin: protocol, host and port. In Docker use DOCKER_FRONTEND_URL; locally use FRONTEND_URL.
401 after restartCheck expiration, consistent JWT key, clock, account status and loss of the in-memory token.
Cannot sign in as adminDemoData does not update existing accounts; check demo mode, volume and the password actually stored.
Changing VITE_API_URL has no effectIt is a build variable. Rebuild frontend. This Dockerfile fixes /api and does not copy .env.local.

To verify deployment, run the HTTP commands and inspect the three services' healthy status with Compose. /api/me must return 401 without a valid token, while / and /usuarios must serve the React application.

CV & portfolio · ES / EN
EspañolEnglish