VPS Tutorials
Nexus Repository on a VPS: Maven, npm, HTTPS and reliable recovery
Deploy a version-pinned Nexus Repository with PostgreSQL and Caddy. Size JVM memory, configure private Maven/npm access, restrict CI credentials, and coordinate database, blob and node-identity backups.

Nexus Repository is a self-hosted artifact service. It caches dependencies from upstream registries such as Maven Central and npm, and stores your team's JARs, packages and build outputs. For Jenkins, GitHub Actions and multiple developer machines, its value is shared dependency caching, controlled private publishing and reproducible builds—not simply somewhere to upload ZIP files.
This guide uses Ubuntu 24.04, Docker Compose, Nexus Repository Community Edition, PostgreSQL and Caddy. It covers repository setup, least-privilege CI access, monitoring, coordinated backups, recovery and upgrades. The stack remains a single-node service: backups and a recovery plan are essential.
Version context: the September 2026 source used
3.96.0, pinned as3.96.0-alpine; that is a historical example, not a claim that it remains the latest release. The default image moved to Alpine from 3.91.0. Current official documentation includes the 3.98.x line. Review release notes and security fixes before selecting a production tag; do not perform unattended upgrades withlatest. In particular, 3.98.0 had a PostgreSQL custom-schema upgrade issue fixed in 3.98.1. This example uses a custom schema, so that warning matters.
Consider it when you need to:
- Cache frequently downloaded Maven/npm dependencies across projects.
- Publish internal JARs, parent POMs, frontend components or CLI packages.
- Give Jenkins, GitHub Actions and self-hosted runners one artifact endpoint.
- Authorize downloads, uploads and deletion separately, with clear audit boundaries.
- Complete a toolchain already using Jenkins CI/CD, Harbor or SonarQube.
For one person and one project with little cache reuse, a managed artifact service may save considerable maintenance time. Nexus is most useful when clients share caches and private packages. It is not a general-purpose file drive or a replacement for object storage.
| Service | Main content | Typical clients | Relationship to Nexus |
|---|---|---|---|
| Nexus Repository | Maven, npm, PyPI, NuGet, Raw artifacts and proxy caches | Maven, Gradle, npm, CI | The service covered here |
| Harbor | OCI/Docker images, signatures and vulnerability scans | Docker, Podman, Kubernetes | More focused on container images |
| Gitea/GitLab | Git history, issues and merge requests | Git, IDEs, CI | Not a general artifact proxy replacement |
| S3/object storage | File objects | SDKs, rclone, applications | Does not supply package indexes and proxy semantics |
Use Harbor for image scanning, replication and project isolation. Nexus is useful when you also need several language ecosystems. A common arrangement is Harbor for OCI images and Nexus for packages; they can coexist.
The source's older “2 vCPU, 8 GB RAM, 20 GB local blobs” description must not be treated as the current official small profile. The current reference architecture lists an extra-small Nexus node at 4 vCPU and 16 GiB RAM, and a small node at 8 vCPU and 32 GiB, with database resources considered separately. These throughput profiles are planning references, not guarantees for a low-cost VPS.
| Use | Practical starting point | Database | Limits |
|---|---|---|---|
| Short evaluation | An older 2 vCPU / 4 GB trial may start | H2 in a supported non-container setup | Not the production Docker path below |
| Low-volume team using this unchanged JVM example | 4 vCPU / 16 GB RAM / 100 GB+ NVMe | PostgreSQL | Measure the complete stack and artifact growth |
| Busy CI | 16 GB+ Nexus memory with workload-appropriate CPU/storage | Separately sized PostgreSQL | Monitor IOPS, cache hits and concurrency |
| Large or highly available installation | Official reference architecture | External PostgreSQL | A single VPS cannot provide HA |
Reserve roughly one-third of memory for the operating system, buffers and other processes, as Sonatype recommends. The sample allocates a 4 GB heap plus up to 4 GB direct memory: that does not fit safely on an 8 GB host alongside PostgreSQL. Use sufficient RAM, or explicitly tune lower limits after measuring a small workload. An OOM is not a reason to keep increasing the heap on the same host.
Budget storage for private artifacts, proxy growth, backup copies and upgrade workspace. Sonatype requires at least 4 GB free space; falling below it can make the database read-only. Maven and image stores can readily reach hundreds of GB. Alert around 70% usage and leave time to clean up or expand.
New installations default to embedded H2. Official limitations are 200,000 requests per day or 100,000 components, and container-based H2 deployments are unsupported. PostgreSQL is the recommended production choice, and this guide connects it on the first startup rather than creating an H2 instance to migrate later.
Keep the database close to Nexus, preferably on the same host for this small setup or in the same cloud region. The database account must own its database because upgrades alter the schema. Install pg_trgm; a missing extension or insufficient ownership can prevent migrations.
Use a dedicated hostname such as repo.example.com, with A/AAAA records pointing at the VPS. Open only the required services:
22/tcp: SSH, preferably restricted to management IPs.80/tcp: ACME HTTP validation and HTTPS redirects.443/tcp: the UI and package-client endpoint.8081/tcp: Docker networks only, without a public host mapping.5432/tcp: Docker networks only, without a public host mapping.
Check DNS and the host's public address:
export NEXUS_DOMAIN="repo.example.com"
getent ahosts "$NEXUS_DOMAIN"
curl -4 https://ifconfig.me
Fix stale A records and unusable AAAA records before requesting certificates. Exposing Nexus or PostgreSQL directly is not an appropriate workaround for broken DNS or proxy configuration.
Use Docker's official Ubuntu apt repository. Skip this section if both Engine and the Compose plugin are already installed and verified:
sudo apt-get update
sudo apt-get install -y ca-certificates curl
sudo install -m 0755 -d /etc/apt/keyrings
sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
sudo chmod a+r /etc/apt/keyrings/docker.asc
echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "$VERSION_CODENAME") stable" | sudo tee /etc/apt/sources.list.d/docker.list >/dev/null
sudo apt-get update
sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
sudo systemctl enable --now docker
sudo docker version
sudo docker compose version
The project lives at /opt/nexus. The official Nexus container writes as UID 200 to /nexus-data; a named volume avoids most bind-mount ownership mistakes.
The original directory/password commands are:
sudo install -d -m 0750 /opt/nexus
cd /opt/nexus
umask 077
openssl rand -base64 36 | tr -d '\n' | sudo tee /opt/nexus/.postgres-password >/dev/null
sudo chmod 600 /opt/nexus/.postgres-password
A root-owned 0750 directory prevents an ordinary maintainer from entering it. Before that sequence, create the directory with the maintainer as owner:
sudo install -d -m 0750 -o "$(id -u)" -g "$(id -g)" /opt/nexus
cd /opt/nexus
Create /opt/nexus/.env, replace the sample hostname, and obtain POSTGRES_PASSWORD from the generated secret:
cd /opt/nexus
POSTGRES_PASSWORD_VALUE="$(sudo cat /opt/nexus/.postgres-password)"
sudo tee /opt/nexus/.env >/dev/null <<EOF
NEXUS_VERSION=3.96.0-alpine
NEXUS_DOMAIN=repo.example.com
POSTGRES_DB=nexus
POSTGRES_USER=nexus
POSTGRES_PASSWORD=${POSTGRES_PASSWORD_VALUE}
EOF
sudo chmod 600 /opt/nexus/.env
unset POSTGRES_PASSWORD_VALUE
Keep .env, dumps and the initial admin password out of Git. Use the separate JDBC username/password variables instead of putting special characters inside a URL. The fixed image tag is the source example; check a maintained release before a new deployment.
Create initdb/01-nexus.sql so the owner has a dedicated schema with pg_trgm:
cd /opt/nexus
sudo install -d -m 0750 initdb
sudo tee initdb/01-nexus.sql >/dev/null <<'SQL'
CREATE SCHEMA IF NOT EXISTS nexus AUTHORIZATION nexus;
CREATE EXTENSION IF NOT EXISTS pg_trgm WITH SCHEMA nexus;
SQL
sudo chmod 640 initdb/01-nexus.sql
This SQL contains no secret. Make the mounted file readable by the PostgreSQL container with sudo chmod 644 initdb/01-nexus.sql; root-owned mode 640 can otherwise stop initialization. Initialization scripts run only when the database volume is empty. If an existing volume was initialized incorrectly, inspect and back it up before planning a migration; never delete a production volume to retry this step.
Save the following as /opt/nexus/compose.yaml:
name: nexus-repository
services:
postgres:
image: postgres:17-alpine
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD}
volumes:
- postgres-data:/var/lib/postgresql/data
- ./initdb/01-nexus.sql:/docker-entrypoint-initdb.d/01-nexus.sql:ro
healthcheck:
test: ["CMD-SHELL", "pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB"]
interval: 10s
timeout: 5s
retries: 12
start_period: 20s
networks:
- backend
nexus:
image: sonatype/nexus3:${NEXUS_VERSION}
restart: unless-stopped
depends_on:
postgres:
condition: service_healthy
environment:
NEXUS_DATASTORE_NEXUS_JDBCURL: jdbc:postgresql://postgres:5432/nexus?currentSchema=nexus
NEXUS_DATASTORE_NEXUS_USERNAME: ${POSTGRES_USER}
NEXUS_DATASTORE_NEXUS_PASSWORD: ${POSTGRES_PASSWORD}
INSTALL4J_ADD_VM_PARAMS: >-
-Xms4096m -Xmx4096m -XX:MaxDirectMemorySize=4096m
-Djava.util.prefs.userRoot=/nexus-data/javaprefs
-Dnetworkaddress.cache.ttl=5
volumes:
- nexus-data:/nexus-data
expose:
- "8081"
stop_grace_period: 2m
healthcheck:
test: ["CMD-SHELL", "wget -qO- http://127.0.0.1:8081/service/rest/v1/status >/dev/null || exit 1"]
interval: 20s
timeout: 10s
retries: 30
start_period: 180s
networks:
- backend
- proxy
caddy:
image: caddy:2-alpine
restart: unless-stopped
depends_on:
nexus:
condition: service_healthy
environment:
NEXUS_DOMAIN: ${NEXUS_DOMAIN}
ports:
- "80:80"
- "443:443"
- "443:443/udp"
volumes:
- ./Caddyfile:/etc/caddy/Caddyfile:ro
- caddy-data:/data
- caddy-config:/config
networks:
- proxy
networks:
backend:
internal: true
proxy:
volumes:
postgres-data:
nexus-data:
caddy-data:
caddy-config:
The important properties are:
- A pinned Nexus image, rather than a moving
latesttag. - No public mappings for Nexus 8081 or PostgreSQL 5432.
- Database health gating before Nexus starts.
stop_grace_period: 2mto allow the recommended 120-second graceful stop.- JVM configuration through
INSTALL4J_ADD_VM_PARAMS, as used by images from 3.78 onward. - Java preferences under the persistent data directory.
The backend network is internal, but Nexus also joins the proxy network so it can fetch upstream packages. Keep the sample's 4 GB heap/4 GB direct-memory budget on a sufficiently sized host; the old 8 GB recommendation is not compatible with this full stack. PostgreSQL and Caddy tags should also be resolved to versions approved by your upgrade policy.
Create /opt/nexus/Caddyfile:
{$NEXUS_DOMAIN} {
encode zstd gzip
reverse_proxy nexus:8081 {
header_up Host {host}
header_up X-Real-IP {remote_host}
header_up X-Forwarded-For {remote_host}
header_up X-Forwarded-Proto {scheme}
transport http {
read_timeout 300s
write_timeout 300s
}
}
log {
output stdout
format json
}
}
Enable Nexus's HTTP Forwarded Headers capability. Caddy terminates TLS and forwards the host, client address and protocol. Long read/write timeouts help with large uploads but do not remove storage, client or business-policy limits.
The source validation example is:
cd /opt/nexus
sudo docker compose --env-file .env config >/tmp/nexus-compose.rendered.yaml
sudo docker run --rm -v /opt/nexus/Caddyfile:/etc/caddy/Caddyfile:ro caddy:2-alpine caddy validate --config /etc/caddy/Caddyfile
The standalone container does not inherit the Compose domain variable, and rendered Compose output contains the database secret. Run validation through the service environment instead, and remove any rendered temporary file:
cd /opt/nexus
umask 077
sudo docker compose --env-file .env config --quiet
sudo docker compose --env-file .env run --rm --no-deps caddy \
caddy validate --config /etc/caddy/Caddyfile --adapter caddyfile
rm -f /tmp/nexus-compose.rendered.yaml
cd /opt/nexus
sudo docker compose --env-file .env pull
sudo docker compose --env-file .env up -d
sudo docker compose --env-file .env ps
sudo docker compose --env-file .env logs --tail=200 nexus
The first startup can take several minutes. Follow migrations and health status rather than repeatedly restarting after 30 seconds:
cd /opt/nexus
sudo docker compose --env-file .env exec postgres pg_isready -U nexus -d nexus
sudo docker compose --env-file .env exec postgres psql -U nexus -d nexus -c '\dx'
curl -fsS https://repo.example.com/service/rest/v1/status
curl -fsSI https://repo.example.com/
The \dx output should include pg_trgm. If public HTTPS fails, check DNS, 80/443 and Caddy:
cd /opt/nexus
sudo docker compose --env-file .env logs --tail=200 caddy
sudo ss -lntup | grep -E ':(80|443)\b'
Read the one-time password from /nexus-data/admin.password:
cd /opt/nexus
sudo docker compose --env-file .env exec nexus cat /nexus-data/admin.password
Open https://repo.example.com, log in as admin, and:
- Change the administrator password and store it in a password manager.
- Decide explicitly whether anonymous reads are appropriate.
- Create individual administrative accounts instead of sharing
admin. - Check Repository → Data Store and confirm the JDBC URL uses PostgreSQL.
- Verify HTTP Forwarded Headers under System → Capabilities.
- Configure outgoing email and alert recipients.
Menu labels can differ in newer Nexus One UI releases. The initial password file may disappear after setup; that is normal. Do not paste passwords, screenshots or credential-bearing CI logs into tickets or chat.
hostedstores artifacts your team publishes.proxycaches an upstream registry.groupcombines several repositories into a client read endpoint.
Use a group for downloads, hosted repositories for publishing, and proxy repositories only for upstream caching. You can then adjust upstreams and group membership without changing every project.
Check the usual initial repositories:
maven-central: Maven Central proxy.maven-releases: hosted releases.maven-snapshots: hosted snapshots.maven-public: the combined download endpoint.
Review their blob stores, version policies and deployment policies. Prevent accidental release overwrites and keep snapshots separate.
The source's ~/.m2/settings.xml example is:
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0">
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>https://repo.example.com/repository/maven-public/</url>
</mirror>
</mirrors>
<servers>
<server>
<id>nexus-releases</id>
<username>${env.NEXUS_USERNAME}</username>
<password>${env.NEXUS_PASSWORD}</password>
</server>
<server>
<id>nexus-snapshots</id>
<username>${env.NEXUS_USERNAME}</username>
<password>${env.NEXUS_PASSWORD}</password>
</server>
</servers>
</settings>
For a private group, this misses a server entry matching the mirror ID. Save this complete, secret-free template as ci/settings.xml.tpl, and use it for developer settings too:
<settings xmlns="http://maven.apache.org/SETTINGS/1.2.0">
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*</mirrorOf>
<url>https://repo.example.com/repository/maven-public/</url>
</mirror>
</mirrors>
<servers>
<server>
<id>nexus</id>
<username>${env.NEXUS_USERNAME}</username>
<password>${env.NEXUS_PASSWORD}</password>
</server>
<server>
<id>nexus-releases</id>
<username>${env.NEXUS_USERNAME}</username>
<password>${env.NEXUS_PASSWORD}</password>
</server>
<server>
<id>nexus-snapshots</id>
<username>${env.NEXUS_USERNAME}</username>
<password>${env.NEXUS_PASSWORD}</password>
</server>
</servers>
</settings>
Set the publication endpoints in pom.xml:
<distributionManagement>
<repository>
<id>nexus-releases</id>
<url>https://repo.example.com/repository/maven-releases/</url>
</repository>
<snapshotRepository>
<id>nexus-snapshots</id>
<url>https://repo.example.com/repository/maven-snapshots/</url>
</snapshotRepository>
</distributionManagement>
Verify downloads through Nexus:
export NEXUS_USERNAME="ci-reader"
export NEXUS_PASSWORD="replace-with-secret"
mvn -U -s "$HOME/.m2/settings.xml" dependency:go-offline
Use CI's secret store for real values. Maven reads the environment expressions at runtime; do not commit expanded passwords. A read-only developer account and a publisher account should have different permissions.
Create:
npm-hostedfor internal packages.npm-proxy, with upstreamhttps://registry.npmjs.org.npm-all, withnpm-hostedandnpm-proxyas members in that order.
Point downloads at the group:
npm config set registry "https://repo.example.com/repository/npm-all/"
npm config get registry
npm --loglevel info view lodash version
Set the hosted publication registry explicitly in package.json:
{
"name": "@example/internal-ui",
"version": "1.0.0",
"publishConfig": {
"registry": "https://repo.example.com/repository/npm-hosted/"
}
}
Enable npm Bearer Token Realm under Security → Realms. For npm 9+, use the documented legacy login flow with an existing Nexus account:
npm adduser --auth-type=legacy --registry="https://repo.example.com/repository/npm-hosted/"
npm whoami --registry="https://repo.example.com/repository/npm-hosted/"
npm publish
Do not put plain-text tokens in shell history. The source creates a temporary .npmrc:
set -euo pipefail
umask 077
cat >.npmrc <<EOF
registry=https://repo.example.com/repository/npm-all/
//repo.example.com/repository/npm-all/:_authToken=${NEXUS_NPM_TOKEN}
always-auth=true
EOF
npm ci
rm -f .npmrc
That cleanup does not run when npm ci fails, and its token is scoped only to the group URL. The following version cleans up on exit and supplies separate URL entries for group reads and hosted writes. Give the token only the permissions the job needs; omit publishing from ordinary build jobs. Older npm's always-auth setting is not required by every current client.
set -euo pipefail
umask 077
NEXUS_NPM_CONFIG="$(mktemp)"
trap 'rm -f "$NEXUS_NPM_CONFIG"' EXIT
cat >"$NEXUS_NPM_CONFIG" <<EOF
registry=https://repo.example.com/repository/npm-all/
//repo.example.com/repository/npm-all/:_authToken=${NEXUS_NPM_TOKEN}
//repo.example.com/repository/npm-hosted/:_authToken=${NEXUS_NPM_TOKEN}
EOF
npm ci --userconfig "$NEXUS_NPM_CONFIG"
# Run this only in the release job:
# npm publish --userconfig "$NEXUS_NPM_CONFIG" --registry=https://repo.example.com/repository/npm-hosted/
Separate accounts by purpose:
ci-reader: group reads only.ci-maven-publisher: readmaven-public, publish releases/snapshots.ci-npm-publisher: readnpm-all, publish tonpm-hosted.- Operations administrators: repository, task and security management; never routine builds.
Grant only necessary browse, read, add and edit privileges for the intended repositories. Avoid delete unless the release process truly requires it. Check the exact names in nx-repository-view-<format>-<repository>-<action> rather than granting a broad wildcard.
If your licensed edition supports User Token, use rotatable credentials with an expiry policy. Give each pipeline or team a separate credential so one leak does not require revoking every client. Consult the current edition feature matrix before assuming a commercial feature is available in Community.
Add Jenkins credentials:
nexus-maven: Username with password.nexus-npm-token: Secret text.
The source pipeline illustrates the credential binding:
pipeline {
agent any
stages {
stage('Build and publish') {
steps {
withCredentials([usernamePassword(
credentialsId: 'nexus-maven',
usernameVariable: 'NEXUS_USERNAME',
passwordVariable: 'NEXUS_PASSWORD'
)]) {
sh '''
set -eu
umask 077
envsubst < ci/settings.xml.tpl > ci/settings.xml
mvn -B -s ci/settings.xml clean deploy
rm -f ci/settings.xml
'''
}
}
}
}
}
Replace its shell body with this sequence, using the complete Maven template above. Maven resolves the environment references without envsubst, and the temporary file is removed even after a failed build:
set -eu
umask 077
NEXUS_SETTINGS="$(mktemp)"
trap 'rm -f "$NEXUS_SETTINGS"' EXIT
cp ci/settings.xml.tpl "$NEXUS_SETTINGS"
mvn -B -s "$NEXUS_SETTINGS" clean deploy
Do not enable set -x; it may expose secrets in the console. For an initial CI host, follow the Jenkins VPS guide for HTTPS, webhooks and agent isolation.
Create NEXUS_USERNAME and NEXUS_PASSWORD in Actions secrets. Commit only the secret-free ci/settings.xml.tpl template:
name: publish-maven
on:
push:
tags:
- "v*"
permissions:
contents: read
jobs:
publish:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions/setup-java@v4
with:
distribution: temurin
java-version: "21"
cache: maven
- name: Publish to Nexus
env:
NEXUS_USERNAME: ${{ secrets.NEXUS_USERNAME }}
NEXUS_PASSWORD: ${{ secrets.NEXUS_PASSWORD }}
run: |
set -euo pipefail
umask 077
envsubst < ci/settings.xml.tpl > ci/settings.xml
mvn -B -s ci/settings.xml clean deploy
rm -f ci/settings.xml
Replace this job's run body with the same exit-trapped shell sequence used for Jenkins. Keep its secret environment mapping. Cleanup must execute on failure; a final ordinary rm after Maven is insufficient.
If a hosted runner cannot reach private Nexus, use a same-network self-hosted runner, VPN or zero-trust access. Do not expose the database or management ports for CI convenience. The example uses major Action tags for readability; pin reviewed commit SHAs in production according to your supply-chain policy.
- Apply snapshot retention based on last download and the required version window.
- Clean npm proxy components that have not been downloaded for a long time.
- Keep hosted releases out of automatic deletion unless an approval policy says otherwise.
- Schedule Compact blob store after deletions to reclaim physical space.
- Back up before major cleanup, and run expensive tasks off-peak.
Use separate blob stores or clearly separated policies where useful. Cleanup is not a backup: upstream dependencies can often be fetched again; deleted internal releases need backups or their original build sources.
Cover at least:
- HTTPS and
/service/rest/v1/statusavailability. - Container health, restarts and OOM events.
- Host memory, load, disk usage, inodes and I/O latency.
- PostgreSQL connections, slow queries, autovacuum and backup results.
- Failed Nexus tasks, blob growth and suspicious logins.
- Certificate renewal and HTTP 4xx/5xx rates.
A simple inspection is:
set -euo pipefail
cd /opt/nexus
curl -fsS --max-time 15 https://repo.example.com/service/rest/v1/status >/dev/null
sudo docker compose --env-file .env ps
df -h /var/lib/docker
df -i /var/lib/docker
sudo docker stats --no-stream
Send these signals to a monitoring system for unattended operation. Alerts near 70% and 80% disk usage give more reaction time than waiting for only 4 GB to remain.
PostgreSQL holds metadata; blob stores hold the actual artifacts. You also need the identity under $data-dir/keystores/node/. Backing up only one cannot restore a coherent service. For this single-node installation, the simplest consistent backup is a maintenance window with Nexus stopped while PostgreSQL and the full data volume are copied.
The source /opt/nexus/backup.sh example is retained here for comparison:
#!/usr/bin/env bash
set -euo pipefail
cd /opt/nexus
STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
BACKUP_ROOT="/srv/backups/nexus/${STAMP}"
sudo install -d -m 0700 "$BACKUP_ROOT"
sudo docker compose --env-file .env stop -t 120 nexus
sudo docker compose --env-file .env exec -T postgres \
pg_dump -U nexus -d nexus -Fc >"${BACKUP_ROOT}/nexus-postgres.dump"
NEXUS_VOLUME="$(sudo docker volume ls --format '{{.Name}}' | awk '/nexus-repository_nexus-data$/ {print; exit}')"
test -n "$NEXUS_VOLUME"
sudo docker run --rm \
-v "${NEXUS_VOLUME}:/source:ro" \
-v "${BACKUP_ROOT}:/backup" \
alpine:3.22 \
tar -C /source -czf /backup/nexus-data.tar.gz .
sudo docker compose --env-file .env start nexus
sha256sum "${BACKUP_ROOT}"/* | sudo tee "${BACKUP_ROOT}/SHA256SUMS" >/dev/null
sudo chmod 600 "${BACKUP_ROOT}"/*
echo "Backup complete: ${BACKUP_ROOT}"
Do not use suffix guessing to select a production volume. If a dump fails, that script also exits before restarting Nexus. Replace it with the following root-run script. It resolves the mounted data volume from the running container, prevents overlapping backups, restarts Nexus on failure, and records the environment/configuration privately:
#!/usr/bin/env bash
set -euo pipefail
test "$(id -u)" -eq 0
cd /opt/nexus
umask 077
exec 9>/run/lock/nexus-backup.lock
flock -n 9
NEXUS_STAMP="$(date -u +%Y%m%dT%H%M%SZ)"
NEXUS_BACKUP="/srv/backups/nexus/$NEXUS_STAMP"
install -d -m 0700 "$NEXUS_BACKUP"
NEXUS_CONTAINER="$(docker compose --env-file .env ps -q nexus)"
test -n "$NEXUS_CONTAINER"
NEXUS_DATA_VOLUME="$(docker inspect --format '{{range .Mounts}}{{if eq .Destination "/nexus-data"}}{{.Name}}{{end}}{{end}}' "$NEXUS_CONTAINER")"
test -n "$NEXUS_DATA_VOLUME"
docker volume inspect "$NEXUS_DATA_VOLUME" >/dev/null
docker pull alpine:3.22 >/dev/null
trap 'docker compose --env-file .env start nexus >&2' EXIT
docker compose --env-file .env stop -t 120 nexus
docker compose --env-file .env exec -T postgres \
pg_dump -U nexus -d nexus -Fc >"$NEXUS_BACKUP/nexus-postgres.dump"
docker run --rm \
-v "$NEXUS_DATA_VOLUME:/source:ro" \
-v "$NEXUS_BACKUP:/backup" \
alpine:3.22 tar -C /source -czf /backup/nexus-data.tar.gz .
cp -a .env compose.yaml Caddyfile initdb "$NEXUS_BACKUP/"
docker compose --env-file .env config >"$NEXUS_BACKUP/compose.rendered.yaml"
(
cd "$NEXUS_BACKUP"
sha256sum nexus-postgres.dump nexus-data.tar.gz .env compose.yaml \
Caddyfile initdb/01-nexus.sql compose.rendered.yaml >SHA256SUMS
sha256sum -c SHA256SUMS
)
docker compose --env-file .env start nexus
trap - EXIT
touch "$NEXUS_BACKUP/COMPLETE"
chmod -R go-rwx "$NEXUS_BACKUP"
printf 'Backup complete: %s\n' "$NEXUS_BACKUP"
The trap requests a restart; monitoring must still confirm that Nexus becomes healthy. A backup without the COMPLETE marker is incomplete and must be investigated. The script is specific to this named-volume, local-blob layout; external blob stores need their own coordinated backup procedure.
Enable and test the script:
sudo chmod 750 /opt/nexus/backup.sh
sudo /opt/nexus/backup.sh
sudo find /srv/backups/nexus -maxdepth 2 -type f -printf '%p %s bytes\n' | tail -n 20
Keep all backup files private because the environment and rendered Compose contain credentials. Encrypt and copy the backup off-host. A tar file beside production data on the same disk is not disaster recovery. See the VPS backup and restore drill for restic/rclone integration.
At least monthly, use an isolated VPS or independent Compose project to:
- Run
sha256sum -cagainstSHA256SUMSinside the backup directory. - Restore the PostgreSQL dump to an empty, correctly owned database.
- Restore
/nexus-data, including blobs, configuration and node keystore. - Start with the same Nexus version and matching environment/configuration.
- Log in and download both a cached proxy package and a private hosted package.
- Test actual Maven and npm clients.
- Record RTO, RPO and any failing steps.
Keep Nexus stopped during database restore. Database and blobs must come from the same backup window; mismatched points can produce missing or orphaned artifacts. Keep the restored instance away from production clients until verification is complete.
Treat docker compose pull && up -d as an image operation, not proof of a successful upgrade. Prepare a coordinated backup and save the current environment:
set -euo pipefail
cd /opt/nexus
sudo /opt/nexus/backup.sh
sudo cp .env ".env.before-upgrade-$(date -u +%Y%m%dT%H%M%SZ)"
sudo docker compose --env-file .env pull
sudo docker compose --env-file .env config >/tmp/nexus-upgrade.compose.yaml
Review every intervening upgrade requirement: crossing 3.85 calls for Repair - Rebuild repository search; crossing 3.87 affects custom Java truststores; from 3.91 the Alpine image may lack tools expected by old scripts. For 3.98, check the custom-schema fixes and the default disabling of Groovy script execution before upgrading tasks that depend on it.
Change the pinned version in .env only after clone testing, then use a maintenance window:
cd /opt/nexus
sudo docker compose --env-file .env up -d
sudo docker compose --env-file .env ps
sudo docker compose --env-file .env logs --tail=300 nexus
curl -fsS https://repo.example.com/service/rest/v1/status
Keep rendered configuration in a private temporary file and delete it after use. If an upgrade changes the database schema, switching the image tag back may be unsafe. Restore the pre-upgrade PostgreSQL snapshot and matching /nexus-data, then start the original version. Rehearse this rollback on a clone first.
cd /opt/nexus
sudo docker compose --env-file .env ps
sudo docker compose --env-file .env logs --tail=300 nexus postgres
sudo docker compose --env-file .env exec postgres pg_isready -U nexus -d nexus
Check whether pg_trgm exists, the account owns its database, the JDBC schema is correct, startup migrations are still running, memory is sufficient, and mounted files are readable.
Named volumes are normally initialized by the image. For a deliberate host-directory mount, UID 200 must be able to write:
sudo chown -R 200:200 /srv/nexus-data
sudo find /srv/nexus-data -maxdepth 1 -ls
Do not use chmod -R 777 to hide an ownership error. It broadens access unnecessarily.
Verify Host and X-Forwarded-Proto, and enable HTTP Forwarded Headers. The Caddy reverse proxy guide covers DNS, certificates and forwarded headers.
- Match
distributionManagement's<id>exactly to the settings<server><id>. - Publish to hosted repositories, never a group or proxy.
- Grant add/edit for the intended target.
- Check whether the release already exists and redeployment is disabled.
- Ensure the proxy preserves repository paths and authorization headers.
A private mirror additionally needs the nexus server entry shown above; publication credentials alone do not authenticate group downloads.
Check the npm Bearer Token Realm and --auth-type=legacy for npm 9+. Use the complete /repository/<name>/ URL with a final /. Scope CI authentication separately to group reads and hosted publishing.
Confirm cleanup finished, then compact the corresponding blob store. Back up before large operations and inspect task logs and I/O; avoid repeated heavy compactions during busy CI periods.
- HTTPS works; 8081/5432 are not public.
- Nexus is version-pinned without
latest. - Data Store uses PostgreSQL and
pg_trgmis installed. - Admin credentials are changed; CI has no administrator account.
- Maven reads use
maven-publicand publishing uses hosted repositories. - npm reads use
npm-alland publishing usesnpm-hosted. - Hosted, proxy and group permissions are separated.
- Disk, memory, health, certificates and backup failures alert operators.
- Database, blobs and node identity share a consistent backup point.
- An isolated recovery drill has succeeded.
- Every version change has an upgrade review and recoverable baseline.
A 2 vCPU/4 GB experiment may start, but it is not a production sizing recommendation. Current cloud-native profiles begin at 4 vCPU/16 GiB per extra-small Nexus node. The full local PostgreSQL stack also needs database memory and storage. For the unchanged 4 GB heap/4 GB direct-memory example, plan at least a 16 GB host for low volume, then measure concurrency, cache hits and growth rather than claiming an official throughput guarantee.
Community Edition is available for common individual and small-team artifact workflows, subject to its current license and feature boundaries. Check the current feature matrix; older OSS/Pro articles do not prove today's package formats, HA, enterprise identity or support entitlements.
Yes. Create hosted, proxy and group repositories separately for each format. Read through groups and publish to hosted repositories so permissions, retention and backup requirements remain clear.
Harbor is more focused when the task is OCI images, scanning, signing and replication. Nexus serves multiple package ecosystems. Many teams run both. The Harbor guide describes that complementary image workflow.
Official H2 request/component limits do not establish container support: container-based H2 deployments are explicitly unsupported. Start this Docker stack with PostgreSQL to avoid an unnecessary migration and meet the documented production recommendation.
No. PostgreSQL metadata, blobs and node identity must agree. Stop Nexus during the backup window, capture PostgreSQL and /nexus-data, copy the encrypted result off-host and prove it can be restored. A readable archive alone is only a file copy.
A reliable artifact service combines a maintained pinned release, properly sized memory, PostgreSQL, HTTPS-only ingress, separate read/publish endpoints and narrowly scoped CI credentials. Consistent backups and a tested rollback make those artifacts recoverable.
Watch a week of storage growth and cache hits to set cleanup and expansion thresholds. Then restore a real backup on an independent instance. Those checks show whether the service is sustainable for your team, beyond merely displaying its login page.