---
title: How to Deploy Ory Hydra - Open-Source OAuth 2.0 and OpenID Connect Server
url: https://docs.vultr.com/how-to-deploy-ory-hydra-open-source-oauth-20-and-openid-connect-server
description: Deploy Ory Hydra on a Linux server using Docker Compose with PostgreSQL, Nginx, and Certbot for HTTPS to run a self-hosted OAuth 2.0 and OpenID Connect server.
publish_date: 2026-09-09T03:32:16.008792Z
last_updated: 2026-10-21T22:06:06.619000Z
author: Prosper Ugbovo
header_image: https://lhr1.vultrobjects.com/docs-main-doc-assets-1/2671/4f965fda-e4df-4bb5-b38e-9c386d109c84.png
---

> Index of every Vultr Docs page in markdown: https://docs.vultr.com/llms.txt

[Ory Hydra](https://www.ory.com/hydra) is an open-source OAuth 2.0 Authorization Server and OpenID Connect (OIDC) provider. Unlike identity platforms that bundle user management, Hydra delegates authentication to a separate login and consent application that you control. It handles the OAuth 2.0 authorization code flow, client credentials flow, token introspection, and token revocation through an API-first architecture that separates the authorization protocol from identity storage.

This article explains how to deploy Ory Hydra on a Linux server using Docker Compose with PostgreSQL, Nginx, and a Java-based login and consent application.

## Prerequisites

Before you begin, you need to:

* Have access to a [Linux-based server](https://docs.vultr.com/products/compute/cloud-compute/provisioning) (with at least 2 CPU cores and 4 GB of RAM) as a [non-root user with sudo privileges](https://docs.vultr.com/how-to-create-a-sudo-user-in-linux).
* [Install Docker and Docker Compose](https://docs.vultr.com/how-to-install-docker-on-ubuntu-24-04#install-docker).
* Create a [DNS A record](https://docs.vultr.com/products/network/dns/management/manage-records) pointing to your server's IP address (for example, `hydra.example.com`).

## Set Up the Directory Structure, Configuration, and Environment Variables

Ory Hydra reads its configuration from a YAML file and database credentials and secrets from environment variables at runtime. The directory structure separates the Hydra configuration, the Nginx reverse proxy configuration, and the TLS certificate storage into distinct paths.

1. Create the project directory with all required subdirectories.

    ```console
    $ mkdir -p ~/ory-hydra/{config/nginx,data/{postgres,certbot/conf}}
    ```

    The command creates the following subdirectories:

    * `config/`: Stores the Hydra and Nginx configuration files.
    * `data/postgres/`: Persists PostgreSQL database files across container restarts.
    * `data/certbot/conf/`: Stores the Let's Encrypt TLS certificate files.

1. Navigate to the project directory.

    ```console
    $ cd ~/ory-hydra
    ```

1. Clone the Java reference login and consent application into the project directory.

    ```console
    $ git clone https://github.com/ardetrick/ory-hydra-refrence-java.git reference-app
    ```

    > [!NOTE]
    > If you have your own application that implements the Hydra login and consent protocol, skip this step and replace `./reference-app` in the Docker Compose file with your application's source directory.

1. Generate a system secret for signing tokens and encrypting database records. Hydra requires a secret of at least 16 characters.

    ```console
    $ openssl rand -hex 16
    ```

    Run this command twice and copy both output strings. You use the first value as `YOUR_SYSTEM_SECRET` and the second as `YOUR_PAIRWISE_SALT` (the OIDC pairwise subject identifier salt in the configuration file).

    > [!NOTE]
    > The system secret is written into `hydra.yml` for reference, but the `SECRETS_SYSTEM` environment variable defined in `.env` takes precedence at runtime because Docker Compose passes it directly to the Hydra container. Replace `YOUR_SYSTEM_SECRET` in both files with the same generated value to keep them consistent.

1. Create the Hydra configuration file.

    ```console
    $ nano config/hydra.yml
    ```

1. Add the following content. Replace `hydra.example.com` with your domain name, `YOUR_SYSTEM_SECRET` with the first generated value, and `YOUR_PAIRWISE_SALT` with the second.

    ```yaml
    serve:
      public:
        base_url: https://hydra.example.com/
        cors:
          enabled: true
          allowed_origins:
            - https://hydra.example.com
          allowed_methods:
            - POST
            - GET
            - PUT
            - DELETE
          allowed_headers:
            - Authorization
            - Content-Type
          exposed_headers:
            - Content-Type
          allow_credentials: true
      admin:
        base_url: http://127.0.0.1:4445/

    urls:
      self:
        issuer: https://hydra.example.com/
      login: https://hydra.example.com/login
      consent: https://hydra.example.com/consent
      logout: https://hydra.example.com/logout

    secrets:
      system:
        - YOUR_SYSTEM_SECRET

    oidc:
      subject_identifiers:
        supported_types:
          - public
          - pairwise
        pairwise:
          salt: YOUR_PAIRWISE_SALT

    strategies:
      access_token: opaque

    ttl:
      login_consent_request: 30m
      access_token: 1h
      refresh_token: 720h
      id_token: 1h
      auth_code: 10m

    log:
      level: info
      format: text
      leak_sensitive_values: false
    ```

    Save and close the file.

    * `serve.public`: Sets the public API base URL to the HTTPS path that matches the Nginx reverse proxy. The CORS section restricts cross-origin requests to your domain and specifies the allowed HTTP methods and headers, and permits credentials so the browser includes session cookies with API requests.
    * `serve.admin`: Declares the admin API base URL, used by Hydra when generating self-referencing links in admin responses. The actual network restriction is enforced by the Docker Compose port binding (`127.0.0.1:4445:4445`), which limits the admin API to the loopback interface and prevents access from the public network.
    * `urls`: Tells Hydra where to redirect users during the login and consent steps of the authorization flow. These paths are served by the login and consent app in the Docker Compose stack.
    * `secrets.system`: A secret used to sign access tokens and encrypt sensitive records in the database. Changing this value invalidates all existing tokens.
    * `oidc.subject_identifiers`: Enables both public and pairwise subject identifier types. Public identifiers return the same user ID to all clients. Pairwise identifiers generate a unique, unlinkable user ID per client, which prevents client correlation.
    * `strategies.access_token`: Sets the token format to `opaque`, meaning tokens are random strings that must be validated through the introspection endpoint. The alternative is `jwt`, which allows stateless validation but cannot be revoked before expiry.
    * `ttl`: Configures token lifetimes. Access tokens expire after 1 hour. Refresh tokens expire after 720 hours (30 days). Authorization codes expire after 10 minutes.
    * `log`: Sets the log level to `info` and disables sensitive value exposure to prevent tokens and secrets from appearing in log output.

    > [!NOTE]
    > The admin API `base_url` uses `http://127.0.0.1:4445/` intentionally. The admin API accepts and rejects login and consent requests without authentication, and must never be exposed through the public reverse proxy.

1. Create the Nginx configuration file.

    ```console
    $ nano config/nginx/default.conf
    ```

1. Add the following content. Replace all instances of `hydra.example.com` with your actual domain name.

    ```ini
    server {
        listen 80;
        server_name hydra.example.com;
        return 301 https://$host$request_uri;
    }

    server {
        listen 443 ssl;
        server_name hydra.example.com;

        ssl_certificate /etc/letsencrypt/live/hydra.example.com/fullchain.pem;
        ssl_certificate_key /etc/letsencrypt/live/hydra.example.com/privkey.pem;

        resolver 127.0.0.11 valid=30s;

        # Callback page for the OAuth 2.0 authorization code flow
        location = /callback {
            root /etc/nginx/html;
            try_files /callback.html =404;
        }

        # Login and consent app routes
        location ~ ^/(login|consent|logout|demo) {
            set $login_consent hydra:8080;
            proxy_pass http://$login_consent;
            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;
        }

        # Hydra public OAuth 2.0 and OIDC endpoints
        location / {
            set $hydra hydra:4444;
            proxy_pass http://$hydra;
            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;
        }
    }
    ```

    Save and close the file.

    The first server block listens on port `80` and redirects all HTTP traffic to HTTPS. The second server block listens on port `443` with TLS and contains three location blocks:

    * **`location = /callback`**: Serves the static callback HTML page from the Nginx container's filesystem. Nginx handles this directly without proxying to any upstream service.
    * **`location ~ ^/(login|consent|logout|demo)`**: Routes login, consent, logout, and demo requests to the login and consent app on port `8080`. Hydra redirects users to these paths during the authorization flow to perform authentication and scope approval.
    * **`location /`**: Routes all other requests to the Hydra public API on port `4444`. This covers the OAuth 2.0 authorization endpoint, token endpoint, token revocation endpoint, and the OpenID Connect discovery document at `/.well-known/openid-configuration`.

    Because all services run on the same Docker network, Nginx resolves the container hostname `hydra` through Docker's internal DNS. The `resolver 127.0.0.11 valid=30s` directive tells Nginx to use Docker's internal DNS resolver, which is required when using variables in `proxy_pass` directives. No traffic flows through the host network for these connections.

    The `X-Forwarded-Proto` header on all proxy blocks ensures Hydra recognizes that the original client connection uses HTTPS, which is required for secure redirect generation and cookie handling.

1. Create the callback page that displays the authorization code after a successful OAuth 2.0 flow.

    ```console
    $ nano config/nginx/callback.html
    ```

1. Add the following content.

    ```html
    <!DOCTYPE html>
    <html>
    <head>
      <title>OAuth2 Callback</title>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/3.4.0/vue.global.prod.min.js"></script>
    </head>
    <body>
    <div id="app">
      <div v-if="error">
        <h2>Authorization Failed</h2>
        <p><strong>Error:</strong> {{ error }}</p>
        <p><strong>Reason:</strong> {{ errorDesc }}</p>
      </div>
      <div v-else-if="code">
        <h2>Authorization Successful</h2>
        <p><strong>Code:</strong> <code>{{ code }}</code></p>
        <pre>{{ curlCmd }}</pre>
      </div>
      <div v-else>
        <h2>No code or error received.</h2>
      </div>
    </div>
    <script>
    const { createApp } = Vue;
    const params = new URLSearchParams(window.location.search);
    const code = params.get("code");
    const error = params.get("error");
    const errorDesc = params.get("error_description");
    const origin = window.location.origin;

    createApp({
      data() {
        return {
          code,
          error,
          errorDesc,
          curlCmd: code ? [
            "curl -X POST " + origin + "/oauth2/token \\",
            "  -H 'Content-Type: application/x-www-form-urlencoded' \\",
            "  -d 'grant_type=authorization_code' \\",
            "  -d 'code=" + code + "' \\",
            "  -d 'redirect_uri=" + origin + "/callback' \\",
            "  -d 'client_id=YOUR_CLIENT_ID' \\",
            "  -d 'client_secret=YOUR_CLIENT_SECRET'"
          ].join("\n") : ""
        };
      }
    }).mount("#app");
    </script>
    </body>
    </html>
    ```

    Save and close the file.

    The callback page reads the `code` and `error` query parameters from the URL using the JavaScript `URLSearchParams` API and renders the result using Vue. On a successful flow, it displays the authorization code and a ready-to-run curl command to exchange it for tokens. On a failed flow, it displays the error and reason returned by Hydra.

1. Create the environment variables file.

    ```console
    $ nano .env
    ```

1. Add the following content. Replace `EXAMPLE_DB_PASSWORD` with a strong, unique database password, and replace `YOUR_SYSTEM_SECRET` with the same value you placed in `config/hydra.yml`.

    ```ini
    HYDRA_VERSION=v26.2.0
    POSTGRES_USER=hydra
    POSTGRES_PASSWORD=EXAMPLE_DB_PASSWORD
    POSTGRES_DB=hydradb
    SECRETS_SYSTEM=YOUR_SYSTEM_SECRET
    LOG_LEVEL=info
    ```

    Save and close the file.

## Deploy with Docker Compose

Docker Compose manages all services as a single deployment unit. Certbot runs as a standalone container to obtain the initial TLS certificate before Nginx starts. Port `80` must be available during certificate issuance.

1. Create the Docker Compose file.

    ```console
    $ nano docker-compose.yml
    ```

1. Add the following content.

    ```yaml
    services:
      postgres:
        image: postgres:16-alpine
        environment:
          POSTGRES_USER: ${POSTGRES_USER}
          POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
          POSTGRES_DB: ${POSTGRES_DB}
        volumes:
          - ./data/postgres:/var/lib/postgresql/data
        networks:
          - hydra-network
        restart: unless-stopped
        healthcheck:
          test: ["CMD-SHELL", "pg_isready -U ${POSTGRES_USER} -d ${POSTGRES_DB}"]
          interval: 5s
          timeout: 5s
          retries: 5
        deploy:
          resources:
            limits:
              cpus: '1.0'
              memory: 512M

      hydra-migrate:
        image: oryd/hydra:${HYDRA_VERSION}
        environment:
          - DSN=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
        command: migrate sql -e --yes
        depends_on:
          postgres:
            condition: service_healthy
        networks:
          - hydra-network
        restart: on-failure
        deploy:
          resources:
            limits:
              cpus: '0.50'
              memory: 256M

      hydra:
        image: oryd/hydra:${HYDRA_VERSION}
        ports:
          - "127.0.0.1:4445:4445"
        environment:
          - DSN=postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@postgres:5432/${POSTGRES_DB}?sslmode=disable
          - SECRETS_SYSTEM=${SECRETS_SYSTEM}
          - LOG_LEVEL=${LOG_LEVEL}
        command: serve all --config /etc/config/hydra/hydra.yml
        volumes:
          - ./config:/etc/config/hydra
        depends_on:
          hydra-migrate:
            condition: service_completed_successfully
        networks:
          - hydra-network
        restart: unless-stopped
        deploy:
          resources:
            limits:
              cpus: '1.0'
              memory: 512M

      hydra-login-consent:
        build:
          context: ./reference-app
          dockerfile_inline: |
            FROM gradle:8-jdk21 AS build
            WORKDIR /app
            COPY . .
            ENV GRADLE_OPTS="-Xmx256m -Xms64m -Dfile.encoding=UTF-8"
            RUN gradle bootJar --no-daemon

            FROM eclipse-temurin:21-jre
            WORKDIR /app
            COPY --from=build /app/reference-app/build/libs/*.jar app.jar
            ENTRYPOINT ["java", "-jar", "-Xmx200m", "-Xms64m", "app.jar"]
        depends_on:
          - hydra
        network_mode: "service:hydra"
        restart: unless-stopped
        deploy:
          resources:
            limits:
              cpus: '0.50'
              memory: 512M

      nginx:
        image: nginx:alpine
        ports:
          - "80:80"
          - "443:443"
        volumes:
          - ./config/nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
          - ./data/certbot/conf:/etc/letsencrypt:ro
          - ./config/nginx/callback.html:/etc/nginx/html/callback.html:ro
        depends_on:
          - hydra
          - hydra-login-consent
        networks:
          - hydra-network
        restart: unless-stopped
        deploy:
          resources:
            limits:
              cpus: '0.50'
              memory: 128M

    networks:
      hydra-network:
        driver: bridge
    ```

    Save and close the file.

    * `postgres`: A PostgreSQL 16 database that stores OAuth 2.0 clients, authorization codes, tokens, and consent records. The volume mounted at `./data/postgres` persists data across container restarts. The `healthcheck` polls `pg_isready` every 5 seconds so that dependent services wait for the database to accept connections before starting.
    * `hydra-migrate`: A one-time initialization service that runs database migrations to create the required schema tables. It waits for the `postgres` healthcheck to pass before running, then exits with code `0` after migrations complete. The `hydra` service waits for this container to complete successfully before starting.
    * `hydra`: The main Ory Hydra server. The `serve all` command starts both the public API on port `4444` and the admin API on port `4445`. The admin port is bound to `127.0.0.1` on the host via the `ports` binding (`127.0.0.1:4445:4445`), which restricts access to the loopback interface and prevents exposure on public network interfaces. The public API on port `4444` is accessible only through the Docker network, where Nginx routes external traffic. The `SECRETS_SYSTEM` environment variable overrides the value in `hydra.yml` at runtime, so the secret Hydra actually uses comes from the environment rather than the configuration file.
    * `hydra-login-consent`: The Java-based reference login and consent application. It builds from the `./reference-app` source using a multi-stage Gradle and Eclipse Temurin Docker build. It provides the `/login`, `/consent`, and `/demo` endpoints that users interact with during the authorization flow. Because it uses `network_mode: "service:hydra"`, it shares the Hydra container's network namespace and reaches the admin API at `127.0.0.1:4445`.
    * `nginx`: An Nginx reverse proxy that terminates TLS and routes external traffic to the Hydra public API and the login and consent app. It is the only service that exposes ports to the host (`80` and `443`), serving as the single entry point for all external traffic.

    All services connect to a shared `hydra-network` bridge network, which allows inter-container communication using service names as hostnames. Each service includes a `deploy.resources.limits` block that caps CPU and memory usage, preventing a misbehaving container from starving other services on the host.

    > [!NOTE]
    > The PostgreSQL Data Source Name (DSN) uses `sslmode=disable` because the database connection travels over the internal Docker bridge network, isolated from external traffic. If you move PostgreSQL to a separate host, change `sslmode=disable` to `sslmode=require` and configure TLS certificates on the PostgreSQL server.

1. Run Certbot as a Docker container in standalone mode to get a TLS certificate from Let's Encrypt. Replace `admin@example.com` with your email address and `hydra.example.com` with your domain name.

    ```console
    $ docker run --rm -p 80:80 \
        -v ~/ory-hydra/data/certbot/conf:/etc/letsencrypt \
        certbot/certbot certonly --standalone \
        --non-interactive --agree-tos --no-eff-email \
        --email admin@example.com \
        -d hydra.example.com
    ```

    Certbot starts a temporary web server on port `80`, completes the ACME domain verification challenge, and saves the certificate files. After verification, the container exits and removes itself.

1. Check that the certificate files exist. Replace `hydra.example.com` with your domain name.

    ```console
    $ sudo ls ~/ory-hydra/data/certbot/conf/live/hydra.example.com/
    ```

    Verify that the output lists `fullchain.pem`, `privkey.pem`, `chain.pem`, `cert.pem`, and `README`. These files are mounted into the Nginx container as a read-only volume, wh