Deploying a Next.js and PostgreSQL Application on a VPS: Docker, Nginx, HTTPS, and Production Operations
Getting an application to run on localhost is a different problem from keeping it available on a public domain. Locally, the developer controls the runtime, configuration, network, and database. In production, those responsibilities extend to server access, container networking, TLS certificates, persistent storage, deployment updates, and recovery when something fails. A Next.js application connected to PostgreSQL illustrates this clearly. The application server processes requests and executes application logic. PostgreSQL stores durable application data. Docker provides a repeatable runtime, Nginx routes public traffic, and HTTPS protects communication between the browser and the server. This article follows a practical single-VPS architecture and explains how its components fit together. The configuration examples are reference implementations that must be adapted to the application's actual package manager, database schema, domain, and deployment environment. The goal is not…
// TABLE OF CONTENTS+
Deploying a Next.js and PostgreSQL Application on a VPS
Getting an application to run on localhost is a different problem from keeping it available on a public domain. Locally, the developer controls the runtime, configuration, network, and database. In production, those responsibilities extend to server access, container networking, TLS certificates, persistent storage, deployment updates, and recovery when something fails. A Next.js application connected to PostgreSQL illustrates this clearly. The application server processes requests and executes application logic. PostgreSQL stores durable application data. Docker provides a repeatable runtime, Nginx routes public traffic, and HTTPS protects communication between the browser and the server. This article follows a practical single-VPS architecture and explains how its components fit together. The configuration examples are reference implementations that must be adapted to the application's actual package manager, database schema, domain, and deployment environment. The goal is not merely to make the homepage load. It is to build a deployment that can be inspected, updated, secured, and recovered without accidentally losing application data.
1. Understand the Production Architecture
A useful deployment begins with clearly defined responsibilities. Each component should have a specific job, a limited network boundary, and an understandable failure mode. For this architecture, Nginx runs on the Linux host and accepts public HTTP and HTTPS traffic. It forwards application requests to a Next.js container listening on an internal Docker network. Next.js communicates with a PostgreSQL container over that network. PostgreSQL stores its data in a persistent volume rather than depending on the temporary filesystem of a running container. The browser never needs to connect directly to PostgreSQL. Likewise, the database does not need a public IP address or an internet-accessible database port. This separation reduces accidental exposure and makes troubleshooting easier. If the homepage returns a gateway error, the investigation can begin at Nginx and proceed toward the application. If the application responds but database-backed pages fail, attention can shift to the application logs, database connection, and PostgreSQL health.
2. Prepare the Linux VPS
A virtual private server provides a Linux environment that the developer or administrator can configure directly. That flexibility comes with responsibility: operating-system updates, firewall rules, access control, disk capacity, container lifecycle management, and recovery planning all become part of operating the application. Before deploying, confirm the server's operating system, available memory, disk capacity, architecture, public IP address, and DNS configuration. The required resources depend on the application, traffic, build process, and PostgreSQL workload. A Next.js build may consume substantially more memory than the application needs after startup, so runtime memory alone is not a sufficient sizing estimate. Use a dedicated, non-root administrative account for routine server work. Configure SSH authentication appropriately, apply security updates, and restrict inbound ports to those required by the service. Ordinarily, a public web server needs ports 80 and 443, while SSH access should be limited according to the server's administration requirements. Install Docker Engine and the Docker Compose plugin using the official instructions for the selected Linux distribution. Avoid copying installation commands intended for another distribution without checking package names and repository configuration. The initial objective is a predictable server environment. Application-specific deployment should begin only after the operating system, administrative access, firewall, and Docker installation are understood.
docker --version
docker compose version
docker infoThese commands verify that Docker and Compose are installed and that the Docker daemon is accessible to the current user. If docker info reports a permissions error, resolve the access configuration instead of assuming that the daemon is unavailable. Membership in the Docker group can confer privileges comparable to root access. Treat access to the Docker daemon as privileged administrative access, not as an ordinary application permission. Before exposing the application, confirm that DNS points to the intended VPS and that the provider's network firewall and the operating system's firewall agree about which ports are permitted.
3. Containerize the Next.js Application
Docker packages an application and its runtime dependencies into an image. A container is a running instance of that image with its own process environment, filesystem view, network configuration, and resource constraints. This helps make deployments more repeatable, but it does not automatically make them secure or reliable. The image still needs appropriate dependencies, runtime configuration, permissions, and a clear startup command. For a conventional server-rendered Next.js application, the standalone output mode can reduce the runtime image by copying the files required to run the production server. It is a useful starting point for a self-hosted deployment. Next.js +1 Enable standalone output in the existing Next.js configuration, preserving any configuration already required by the application.
// next.config.js
/** @type {import('next').NextConfig} */
const nextConfig = {
output: "standalone",
};
module.exports = nextConfig;A multi-stage Dockerfile separates dependency installation, compilation, and the production runtime. This avoids carrying the entire development toolchain into the final container. The following example assumes npm and an npm lockfile. It also assumes the application has the required public assets directory. Projects using pnpm, Yarn, native dependencies, monorepo workspaces, or additional runtime assets need corresponding changes.
FROM node:22-alpine AS dependencies
WORKDIR /app
COPY package.json package-lock.json ./
RUN npm ci
FROM node:22-alpine AS builder
WORKDIR /app
COPY --from=dependencies /app/node_modules ./node_modules
COPY . .
RUN npm run build
FROM node:22-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production
ENV PORT=3000
ENV HOSTNAME="0.0.0.0"
RUN addgroup -S nextjs && adduser -S nextjs -G nextjs
COPY --from=builder --chown=nextjs:nextjs \
/app/public ./public
COPY --from=builder --chown=nextjs:nextjs \
/app/.next/standalone ./
COPY --from=builder --chown=nextjs:nextjs \
/app/.next/static ./.next/static
USER nextjs
EXPOSE 3000
CMD ["node", "server.js"]The dependency stage uses npm ci to install the versions recorded in the lockfile. The builder compiles the application, while the runner copies the standalone output and static assets into a smaller runtime environment. The final container runs as a non-root user, reducing the privileges available to the application process. The image still needs to be tested against the real application, especially if it writes files, uses native modules, requires certificates, or performs runtime image optimization. Pinning a compatible Node.js major version is a starting point, not a complete update strategy. Select a supported, patched image appropriate for the project and rebuild regularly to receive security fixes. Standalone output also does not mean every file in the repository is automatically available at runtime. Next.js output tracing may need configuration when application code loads files dynamically or accesses assets outside the traced dependency graph. Next.js +1
node_modules
.next
.git
.env
.env.*
!.env.example
npm-debug.log*Save these entries in .dockerignore. They prevent local dependencies, previous build output, Git history, and environment files from being sent unnecessarily to the Docker build context. The exclusion of .env files is particularly important. Build contexts and intermediate image layers can expose files to people or systems that should never receive production secrets. Environment files should be supplied through the deployment environment, not copied into the image. The exception above retains an example template for documenting required variable names without supplying actual credentials.
4. Run PostgreSQL with Persistent Storage
PostgreSQL requires a durable place to store its database files. A running container has a writable filesystem, but that filesystem belongs to the container's lifecycle. Replacing the container must not mean replacing the database. A Docker named volume provides a storage location managed separately from the container. When a PostgreSQL container is recreated with the same volume mounted at the correct data directory, its database files can remain available. This distinction matters during normal deployments. Rebuilding the Next.js image should not modify the database's persistent storage. Recreating the PostgreSQL container should also preserve data when the correct volume is reused. However, a volume is not a backup. It can still be lost through operator error, disk failure, host failure, filesystem corruption, or removal of the volume itself. Durable storage and recoverable backups are separate requirements. For a single-VPS architecture, PostgreSQL should normally remain on a private Docker network without a published public port. The application connects using the Compose service name and the database's internal port, rather than localhost or the public IP address.
5. Connect the Services with Docker Compose
Docker Compose defines multiple services and the resources connecting them in one configuration. It is a practical fit for a modest application running on a single VPS because it makes service definitions, environment variables, networks, volumes, and startup dependencies explicit. The following example contains two application services: Next.js and PostgreSQL. Nginx is deliberately excluded because this reference architecture runs Nginx on the host. If the actual deployment runs Nginx in a container, its service and network configuration will need to change. The database service has a named volume and a health check. The application waits for PostgreSQL to become healthy before it starts. This improves initial startup behavior, but it does not replace retry logic in the application or protect against later database outages.
services:
web:
build:
context: .
dockerfile: Dockerfile
restart: unless-stopped
environment:
NODE_ENV: production
PORT: "3000"
HOSTNAME: "0.0.0.0"
DATABASE_URL: ${DATABASE_URL:?Set DATABASE_URL}
ports:
- "127.0.0.1:3000:3000"
depends_on:
db:
condition: service_healthy
networks:
- app_network
db:
image: postgres:17
restart: unless-stopped
environment:
POSTGRES_DB: ${POSTGRES_DB:?Set POSTGRES_DB}
POSTGRES_USER: ${POSTGRES_USER:?Set POSTGRES_USER}
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?Set POSTGRES_PASSWORD}
volumes:
- postgres_data:/var/lib/postgresql/data
healthcheck:
test:
- CMD-SHELL
- pg_isready -U "$$POSTGRES_USER" -d "$$POSTGRES_DB"
interval: 10s
timeout: 5s
retries: 5
start_period: 10s
networks:
- app_network
networks:
app_network:
volumes:
postgres_data:The web container's port is bound to the host's loopback interface, making it reachable from host-level Nginx without intentionally publishing port 3000 on every host interface. PostgreSQL has no published port at all. Inside the Compose network, the application uses the hostname db to reach PostgreSQL. The hostname is the service name, not the container's changing IP address. The connection string therefore uses the database service name, the internal port 5432, and the configured database credentials. The example uses a PostgreSQL major-version tag for readability. For a more controlled production deployment, choose an appropriate supported image version and manage upgrades deliberately. PostgreSQL major upgrades may require a migration or upgrade procedure; changing the image tag alone is not a complete database upgrade plan. There is another important detail: depends_on with a health condition governs initial startup ordering. It does not guarantee that PostgreSQL will remain healthy for the lifetime of the application. The application should handle connection failures, timeouts, and reconnection according to the database driver and ORM it uses.
6. Configure Environment Variables and Secrets
A deployment needs configuration that differs between development and production. The database hostname, connection credentials, authentication secrets, external service keys, and public application URL should not be scattered across source files. An environment file can hold deployment-specific values outside the image. For example, a private .env file used by Compose might define POSTGRESDB, POSTGRESUSER, POSTGRESPASSWORD, and DATABASEURL. It should be readable only by the appropriate administrative account, excluded from version control, and backed up only through a deliberate secrets-management process. The database password and the connection string must agree. If a password contains characters with special meaning in a URL, encode them correctly in the connection string rather than assuming the raw password can always be inserted unchanged. Next.js distinguishes server-only environment variables from public variables. Variables prefixed with NEXTPUBLIC may be inlined into browser-side JavaScript during the build. Never place a database password, signing secret, or private API key in a public variable. Next.js +1
POSTGRES_DB=appdb
POSTGRES_USER=appuser
POSTGRES_PASSWORD=replace-with-a-strong-secret
DATABASE_URL=postgresql://appuser:replace-with-a-strong-secret@db:5432/appdbEnvironment variables also have different lifecycles. Some values are read while building the application, while others are read when the server starts or handles a request. If a value is compiled into the browser bundle, changing the runtime environment may not update the already-built JavaScript. Before promoting an image between environments, identify which variables are build-time configuration and which can be supplied at runtime. This matters for a single image promoted from staging to production, where secrets and database endpoints must not be embedded into the artifact. A reliable configuration strategy includes an example environment file, a list of required variables, validation for missing values, and clear separation between public settings and server-only secrets. That makes deployment failures easier to diagnose and reduces the risk of silently running with incorrect defaults.
7. Configure Nginx as the Reverse Proxy
The application container should not be responsible for every concern associated with public HTTP traffic. A reverse proxy provides a controlled entry point, forwards requests to the application, and can handle TLS termination, request limits, and connection-level settings. In this architecture, Nginx runs directly on the VPS. It listens on the public HTTP and HTTPS ports and forwards requests to Next.js at 127.0.0.1:3000. The application continues to run in its container, while Nginx manages the public-facing connection. This arrangement means that the browser communicates with Nginx, not directly with the internal application service. Nginx then creates or forwards the upstream connection to the application. Next.js recommends placing a reverse proxy in front of a self-hosted server because the proxy can help handle malformed requests, slow connections, payload-size limits, and rate limiting. Those protections still require deliberate configuration; merely installing Nginx does not activate every security control automatically. Next.js
server {
listen 80;
server_name example.com www.example.com;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
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;
}
}Replace example.com and www.example.com with the actual domain names. This initial configuration demonstrates request forwarding; it is not yet a complete HTTPS configuration. The forwarding headers communicate the original request host, client address chain, and scheme to the upstream application. Applications should trust forwarded headers only when they originate from a known, controlled proxy. Incorrect proxy trust can cause errors in redirects, secure-cookie behavior, client IP handling, and URL generation. The proxy's connection to Next.js uses the host's loopback address because the example publishes the container port only on 127.0.0.1. If Nginx runs in a separate container instead, the upstream address should normally be the application service name on a shared Docker network. For routes that use streaming responses, review the proxy's buffering behavior. Next.js documents that Nginx may need buffering disabled for streaming to work end to end. Do not apply streaming-specific settings indiscriminately without checking the application's requirements. Next.js
8. Enable HTTPS and Verify Certificate Renewal
HTTPS protects traffic between clients and the public-facing server using TLS. A valid certificate helps browsers verify that they are communicating with the expected domain, while TLS encrypts traffic in transit. A common setup uses a certificate issued by a trusted certificate authority and Nginx configured to present it. Before requesting a certificate, ensure that the domain resolves to the VPS and that the necessary public ports can reach the server. DNS mistakes, firewall rules, an incorrect server name, or an existing proxy configuration can interfere with certificate validation. After certificate issuance, configure Nginx to listen on port 443 with the certificate and private key, then redirect ordinary HTTP requests to HTTPS. The private key must remain protected and should not be committed to the application repository. Certificate issuance is not the end of the task. Certificates expire, so renewal must be configured and tested. A server that worked on deployment day can later fail if renewal stops working unnoticed.
server {
listen 80;
server_name example.com www.example.com;
return 301 https://$host$request_uri;
}
server {
listen 443 ssl;
server_name example.com www.example.com;
ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
location / {
proxy_pass http://127.0.0.1:3000;
proxy_http_version 1.1;
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;
}
}The certificate paths in this example assume certificates were issued and stored at the stated locations. They are not universal paths for every certificate-management arrangement. Configure certificate issuance and renewal using the official documentation for the chosen certificate client and operating system. Before reloading Nginx after a configuration change, validate its syntax. Then verify that the site loads over HTTPS, HTTP redirects correctly, and the certificate matches the requested domain. A browser's padlock is not a full security audit. It confirms aspects of the secure connection, but it does not prove that database access is private, secrets are protected, backups work, or the application has no vulnerabilities.
9. Deploy Updates Without Losing Control
A deployment should be a repeatable procedure rather than a collection of commands remembered from the last successful release. The basic lifecycle is to obtain the intended source revision, validate configuration, build the production image, recreate the application container, and verify the result. For a small VPS, a straightforward Compose workflow may be sufficient. Larger applications may benefit from a CI pipeline that runs tests, builds an image, records its version, and deploys a known artifact. Either approach should make it possible to identify which revision is currently running. Before changing production, review database migrations and any configuration changes. A new application version may expect a column that does not yet exist, while an older version may fail after a destructive schema change. Backward-compatible migrations reduce the risk of a deployment leaving the application and database in incompatible states. Docker Compose supports rebuilding and recreating an individual service. Rebuilding the application service does not inherently require recreating PostgreSQL, provided the deployment configuration and dependencies do not trigger unnecessary changes. Docker Docs
# Validate the rendered Compose configuration
docker compose config -q
# Build the application image
docker compose build web
# Recreate the application service
docker compose up -d --no-deps web
# Inspect running services
docker compose ps
# Review recent application logs
docker compose logs --tail=100 webThese commands illustrate the deployment sequence, not a universal release script. They assume the correct Compose project, environment variables, source revision, and production configuration are already selected. A successful build does not prove that the application can connect to PostgreSQL. A running container does not prove that the public domain is reachable. After deployment, test the application through the same public URL that real users will access. Check both static pages and routes that depend on server-side data. Verify authentication, forms, database writes, error handling, and any background tasks the application actually uses. Confirm that logs contain no new configuration errors and that the expected application revision is running. Avoid destructive shortcuts such as deleting all Docker volumes to solve an application startup problem. Volumes can contain the only copy of production data. Troubleshoot the failing service and inspect the storage configuration before considering any operation that removes persistent resources.
10. Diagnose Deployment Failures Systematically
Production troubleshooting becomes easier when each symptom is mapped to the layer most likely responsible. Start with the observed error, gather logs and configuration evidence, and narrow the investigation. Randomly restarting every service can temporarily hide the cause and make it harder to understand what actually failed. A useful first distinction is whether the failure occurs before a request reaches Next.js, while the application processes it, or when the application accesses PostgreSQL. A DNS error points toward name resolution. A gateway error often indicates an upstream or proxy problem. A successful homepage combined with failed data operations may point toward database connectivity, credentials, schema compatibility, or application logic. These are diagnostic starting points, not definitive conclusions. For example, a gateway error can result from an application crash, a wrong upstream port, a timeout, or a proxy configuration problem. Logs and direct health checks are needed to distinguish them.
| Symptom | Possible causes | Useful first checks |
|---|---|---|
| Domain does not resolve | Incorrect DNS records or stale resolver cache | Check DNS records and resolve the hostname |
| Nginx returns 502 | Application unavailable or upstream address incorrect | Inspect Nginx logs and test the upstream |
| Application starts but database queries fail | Incorrect credentials, hostname, schema, or database readiness | Inspect application logs and database health |
| Database data appears missing | Wrong volume, wrong Compose project, or wrong database | Inspect mounts and verify the connected database |
| HTTPS certificate warning | Certificate mismatch, expiry, or incomplete configuration | Inspect the certificate and Nginx configuration |
| Deployment fails during build | Dependency, TypeScript, configuration, or resource error | Read the build output and inspect server resources |
Failure scenario: Nginx returns 502 Bad Gateway
Consider a hypothetical deployment where the domain resolves correctly but Nginx returns 502 Bad Gateway. That response suggests Nginx could not successfully obtain a valid response from its upstream. It does not, by itself, establish why. First, inspect whether the web service is running and review its recent logs. Then test whether the expected upstream is reachable from the host. If the container publishes port 3000 only on loopback, the host should be able to connect to 127.0.0.1:3000 while external clients cannot directly access that binding. Next, compare the upstream address in Nginx with the Compose port mapping. A mismatch between the container's listening port, the host's published port, and the proxy destination can break the request path even when all services appear to exist. If the application is repeatedly exiting, inspect the application logs rather than repeatedly reloading Nginx. A proxy configuration cannot repair an application process that crashes during startup.
sudo nginx -t
sudo tail -n 100 /var/log/nginx/error.log
docker compose ps
docker compose logs --tail=100 web
curl -I http://127.0.0.1:3000/Failure scenario: the application cannot connect to PostgreSQL
A second hypothetical failure occurs when the application starts but database-backed routes return errors. Check the connection string before changing the database server. Inside a Compose network, localhost refers to the application container itself, not the PostgreSQL service. The hostname should normally be the Compose service name, such as db. Also verify that the configured database name, username, and password match the initialized database. Changing the environment variables for an existing PostgreSQL data directory does not necessarily recreate the database user or change an existing password. Initialization variables are primarily used when setting up a new database directory. If PostgreSQL is healthy but authentication fails, investigate credentials and existing database state. If the database is still starting, inspect health-check output and application retry behavior. The correct fix depends on the evidence.
Failure scenario: the database appears empty after a redeployment
An apparently empty database is a data-integrity problem, not simply a container startup issue. Possible explanations include using a different Compose project with a different named volume, mounting the wrong storage location, connecting to another database, or having initialized a new empty database directory. Do not immediately delete volumes, rerun initialization scripts, or overwrite the current database. First inspect the Compose project, the mounted volume, the database connection target, and the available backups. Compare the expected database name and the actual data returned by a read-only query. If a previous database volume still exists, recovery may be possible, but the exact steps depend on the storage state and PostgreSQL version. Preserve available copies before making changes. A deployment that can accidentally point to an empty database needs a clearer storage and environment-selection process.
11. Backups, Restoration, and Database Durability
A persistent volume protects database files from the normal replacement of a container, but it does not provide an independent recovery point. If the VPS fails, the disk becomes corrupted, or an operator removes the volume, the database may become unavailable or unrecoverable. Backups address a different problem. A logical PostgreSQL backup captures database objects and data in a format that can be restored into an appropriate PostgreSQL environment. For many smaller applications, pg_dump is a reasonable starting point. PostgreSQL also provides other backup strategies, including physical backups and continuous archiving, for requirements that need point-in-time recovery. Next.js The right approach depends on how much data the application can afford to lose and how long recovery can take. A small personal portfolio site may tolerate a different recovery window from a transactional application. These limits should be explicit rather than assumed. A backup stored only on the same VPS is vulnerable to host-level failure. Copy backups to independent storage, restrict access to them, and encrypt them where appropriate. Database backups may contain personal data, authentication records, and other sensitive information; treat them as production data rather than harmless files.
mkdir -p backups
chmod 700 backups
docker compose exec -T db \
pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" \
> backups/appdb-$(date +%F-%H%M%S).sqlThis example demonstrates the general idea, but the shell variables must actually be defined in the shell running the command. Values stored only in a Compose .env file are not automatically exported into every interactive shell. Use a deliberate backup script or an approved secret/configuration mechanism to supply the correct database name and username. For production use, make the script fail safely, capture command errors, protect the backup directory, and verify that a usable backup file was produced. Plain SQL output is convenient for inspection and restoration, but may be large. A custom-format dump produced with pgdump -Fc can be restored using PostgreSQL's pgrestore utility. A backup process should also account for retention, transfer to independent storage, disk-space monitoring, and notification when a scheduled run fails. A command that worked once is not a backup strategy.
Test restoration, not just backup creation
The strongest practical test of a backup is to restore it into an isolated test database and verify that the expected tables and records are present. A file existing on disk proves only that a file was written; it does not prove that the backup can be restored successfully. Document the database version, required extensions, restoration procedure, and any application migrations needed after recovery. If the application relies on object storage or external services in addition to PostgreSQL, those dependencies may need their own recovery plan. A useful operational exercise is to rehearse recovery before it is urgently needed. Record how long the restoration took and whether the application could resume normal operation. Those observations provide evidence for a realistic recovery objective.
12. Monitor the Application and Protect the Server
A production deployment needs enough visibility to distinguish an isolated error from a recurring operational problem. At a minimum, monitor application availability, container restarts, application logs, Nginx errors, disk usage, memory pressure, database connectivity, and backup completion. Docker's restart policy can bring a container back after certain failures, but restarting is not the same as recovering correctly. A process may repeatedly crash because of a missing environment variable, failed migration, or invalid configuration. Monitor repeated restarts instead of treating them as evidence of a healthy service. Logs should contain useful diagnostic information without exposing credentials, session tokens, or sensitive personal data. Configure retention so logs do not eventually consume the server's available disk space. Likewise, PostgreSQL logs and application logs should be accessible to authorized operators without being exposed publicly. Security also requires keeping the operating system, Docker Engine, base images, Node.js runtime, PostgreSQL, and application dependencies patched. Restrict administrative access, avoid publishing unnecessary ports, and review the permissions of any service that can access production data. A single VPS remains a single point of failure. If its host or underlying storage becomes unavailable, the application and database may both go offline. Monitoring can reveal the outage, but genuine resilience requires an independent recovery environment or a more redundant architecture.
13. Production-Readiness Checklist
- [ ] DNS records point to the intended server.
- [ ] Administrative access and firewall rules have been reviewed.
- [ ] Docker and Docker Compose are installed and functioning.
- [ ] The Next.js image builds successfully from the intended source revision.
- [ ] The application runs without unnecessary root privileges.
- [ ] PostgreSQL is not publicly exposed.
- [ ] Database files are stored in persistent storage.
- [ ] Production secrets are excluded from Git and container build contexts.
- [ ] Nginx forwards requests to the correct application endpoint.
- [ ] HTTPS works for the intended domain and certificate renewal is configured.
- [ ] Application routes and database operations have been tested after deployment.
- [ ] Database migrations have a documented deployment and recovery strategy.
- [ ] Backups are stored independently of the VPS.
- [ ] Restoration has been tested in an isolated environment.
- [ ] Logs, disk capacity, container restarts, and backup failures can be inspected.
- [ ] The deployed application version can be identified.
- [ ] A recovery procedure exists for failed releases and database incidents.
Conclusion
Deploying Next.js and PostgreSQL on a VPS is an exercise in managing boundaries and failure modes. Docker makes application runtimes repeatable, Compose describes how services connect, PostgreSQL volumes preserve database files across container replacement, and Nginx provides a controlled public entry point. HTTPS protects traffic in transit, while independent backups and tested restoration procedures address data recovery. None of these components solves every operational problem by itself. A container can restart without becoming healthy. A persistent volume can be lost with its host. A valid TLS certificate does not guarantee application security. A successful build does not prove that the deployed application can access its database. The difference between a demonstration deployment and a dependable production service lies in how these failure cases are handled. Document the configuration, verify the real request path, preserve data independently, and test recovery before an incident occurs. For a portfolio project, this deployment is also a useful demonstration of engineering beyond application code. The strongest account of the work explains not only which technologies were used, but why each component exists, which risks it addresses, and what evidence shows that the resulting system works.
OPEN
Thoughts on the article.