Serve Web Host with NGINX and Direct Subdomain Docker Server: Port

Abstract: Configure NGINX as a reverse proxy to route specific subdomains directly to Docker containers on custom ports while maintaining security via localhost binding.

Created: 2026-09-05 by

To serve a web host via NGINX while routing specific subdomains directly to a Docker server on a custom port, configure NGINX as a reverse proxy using distinct server_name blocks. This approach isolates traffic for each subdomain, ensuring that requests are forwarded to the correct internal container IP and port without affecting other services or requiring wildcard DNS entries.

Understanding the Architecture

The core challenge in this setup is managing multiple services behind a single public IP address. NGINX acts as the entry point, listening on standard HTTP (port 80) and HTTPS (port 443) ports. It inspects the incoming request's Host header to determine which backend service should handle the traffic. For the main domain or general web hosting, NGINX serves static files or proxies to a primary application. For specific subdomains, such as app.example.com, NGINX forwards the request to a Docker container running on a non-standard port, like 8080 or 3000.

This architecture requires careful configuration of both the Docker networking and the NGINX virtual hosts. The Docker container must be exposed to the host machine’s network interface so NGINX can reach it. Meanwhile, NGINX must be configured with precise location blocks to ensure that only the intended subdomain traffic is proxied to the Docker instance. Incorrect configurations can lead to 502 Bad Gateway errors or security vulnerabilities where unauthorized access to internal services occurs.

Configuring Docker Networking

Before configuring NGINX, ensure your Docker container is accessible from the host system. When running your Docker container, you need to map the internal port to a port on the localhost interface. Use the -p flag when starting the container. For example:

docker run -d --name my-app -p 127.0.0.1:8080:80 my-image

Binding to 127.0.0.1 is crucial for security. It ensures that only processes on the same machine (like NGINX) can connect to the Docker container. If you bind to 0.0.0.0, the port becomes accessible from any external IP, bypassing NGINX’s protection. After starting the container, verify connectivity by running curl http://127.0.0.1:8080. You should receive the response from your application. This step confirms that the Docker side of the equation is correctly set up before touching the web server configuration.

Setting Up NGINX Virtual Hosts

NGINX uses server blocks to define how different domains and subdomains are handled. Create a new configuration file in the /etc/nginx/sites-available/ directory. A typical configuration for a subdomain proxy looks like this:

server {
    listen 80;
    server_name app.example.com;

    location / {
        proxy_pass http://127.0.0.1:8080;
        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 server_name directive explicitly matches the subdomain. This prevents wildcard conflicts where one rule might accidentally catch traffic meant for another service. The proxy_pass directive sends the request to the Docker container. The proxy_set_header lines preserve important client information, such as the original IP address and hostname, which many applications rely on for logging and security checks. After saving the file, create a symbolic link in sites-enabled and reload NGINX using sudo nginx -t to test syntax, followed by sudo systemctl reload nginx.

Handling HTTPS and Security

In production environments, serving content over HTTP is insufficient. You should implement HTTPS using Let’s Encrypt or a similar certificate authority. Tools like Certbot automate the process of obtaining and renewing SSL certificates. When configuring NGINX for HTTPS, ensure that the listen 443 ssl directive is present along with paths to your certificate and key files. Additionally, consider redirecting all HTTP traffic to HTTPS to maintain security standards.

If you are managing multiple subdomains, consider using a shared configuration snippet for common proxy settings to reduce redundancy. This approach minimizes configuration errors and makes maintenance easier. For more complex setups involving dynamic upstream servers, explore advanced load balancing techniques within NGINX. See Setting up Nginx Traffic Redirect for Subdomains on VPS with Multiple Docker Containers and Cloudflare for insights on handling traffic redirection in multi-container environments.

Troubleshooting Common Issues

If you encounter a 502 Bad Gateway error, check if the Docker container is running and listening on the expected port. Verify that NGINX can reach 127.0.0.1:8080 using curl. If the connection times out, ensure that firewall rules allow local loopback traffic, although this is rarely an issue on localhost. Another common problem is incorrect header forwarding. Some frameworks require specific headers to function correctly. Always include X-Real-IP and X-Forwarded-Proto to ensure compatibility with modern web applications.

Additionally, monitor NGINX logs at /var/log/nginx/error.log for detailed error messages. These logs often provide specific reasons why a proxy connection failed, such as permission denied or connection refused. Regularly updating NGINX and Docker versions helps mitigate known vulnerabilities and improves performance stability.

Frequently Asked Questions

Why shouldn't I use wildcard DNS for subdomains?

Wildcard DNS records catch all subdomains, including those you did not intend to route. This can lead to security risks and conflicts with other services that may use the same domain space. Explicitly defining server names in NGINX provides better control and isolation.

How do I debug a 502 Bad Gateway error in NGINX?

Check if the target service is running and accessible via localhost. Verify NGINX error logs for specific failure reasons. Ensure that the proxy_pass URL matches the exact port and protocol used by your backend service.

Can I run multiple Docker containers behind one NGINX instance?

Yes, NGINX can manage multiple backend services by using different server blocks or location paths. Each subdomain or path can be routed to a different container port, allowing efficient resource utilization.

What is the purpose of proxy_set_header directives?

These directives pass client information like IP addresses and original hostnames to the backend server. Many applications rely on this data for logging, analytics, and security checks to function correctly.

Is it safe to expose Docker ports directly to the internet?

No, exposing Docker ports directly bypasses NGINX’s security features and logging. Always bind Docker ports to localhost and let NGINX handle external traffic to protect your infrastructure.

How do I renew SSL certificates automatically?

Use tools like Certbot with automatic renewal hooks. Configure systemd timers or cron jobs to check for certificate expiration and trigger renewal when necessary, ensuring continuous HTTPS availability.

Latest News

How to Display Output of xterm Command in Terminal Screen using Cron

Resolve the inability to display xterm output in a terminal screen from cron by redirecting logs or using wall instead of insecure X11 workarounds.

Read More
Expose Local Server on VPS Preserving Real Client IPs (OS Level)

Resolve VPS logging showing only gateway IPs by configuring reverse proxies to forward real client addresses via X-Forwarded-For headers.

Read More
How to Clear Recent Files History in Linux without Deleting Actual Files?

Clear recent files history in Linux by deleting ~/.local/share/recently-used.xbel without removing the actual files.

Read More
Best HDD Copy Strategy: Manually Syncing and Rewriting Scratch

Resolve data drift between two 4TB hard drives by using rsync with the --delete flag to manually sync and rewrite scratch data for an exact mirror.

Read More
Understanding Bash Prompt Abbreviations: An Overview

Resolve repetitive typing errors by creating and persisting Bash aliases in the .bashrc file for improved command-line efficiency.

Read More
Free Tools and Methods to Log Real-Time Performance Details in Task Manager

Log real-time CPU and memory metrics to CSV files using Windows Performance Monitor Data Collector Sets to troubleshoot system slowness.

Read More
Contact Qatar Airways Customer Service: Phone Number, Help Center, and More

Resolve urgent Qatar Airways reservation issues like flight changes and baggage claims using the US phone number +1801-855-5905 or online self-service tools.

Read More
Windows 11: Alt Codes Displaying Wrong Characters - Solutions

Resolve Windows 11 Alt codes showing wrong characters by verifying the US keyboard layout and enabling Num Lock.

Read More
Run Programs with Elevated Privileges: A Comprehensive Guide

Eliminates the need to type sudo for frequent administrative tasks by configuring .bashrc aliases or functions.

Read More
Dynamically Changing Dates in Excel Formulas Using Cells

Eliminate manual date updates in Excel by using cell references to create dynamic formulas that automatically adjust calculations when input dates change.

Read More
Granting Edit Access to a Specific Excel Sheet in an Office 365 User Email ID-Based Login

Excel Online lacks native sheet-level permissions, so users must split workbooks or use worksheet protection to isolate edit access for specific tabs.

Read More
Creating Network Load on Local Wi-Fi from One PC

Generate sustained Wi-Fi bandwidth load from a single PC using a VM SFTP server to test router stability and throughput.

Read More
Changing the Default Editor for Batch Files in Windows 11's File Explorer

Resolve the issue of batch files opening in Notepad by changing the default editor to a preferred application like VS Code.

Read More
Gain WiFi Connection Minutes Before Losing it by Changing MAC Address

Bypass MAC address filtering to restore WiFi connectivity temporarily when a device is blocked by network administrators.

Read More
Photos Folders Turned Black: Troubleshooting Picture Applications on Windows

Resolve black screens in Windows Photos by resetting the app, updating graphics drivers, and repairing system files.

Read More
Troubleshooting High CPU Temperature Values: A Step-by-Step Guide

Resolve high CPU temperatures and thermal throttling by monitoring with Speedfan, cleaning dust from cooling components, and replacing degraded thermal paste.

Read More
Make cURL establish TLS connection with CA unknown

Resolve cURL TLS connection failures with unknown or self-signed certificates by using the --insecure flag to bypass CA validation.

Read More
Troubleshooting Incorrect Network Metrics Values in Grafana, Prometheus, InfluxDB, and Telegraf

Fix incorrect network metrics in Grafana, Prometheus, InfluxDB, and Telegraf by verifying interface selection, resolving unit mismatches, and handling counter resets.

Read More
Start Another Terminal Window (cmd.exe) Windows Repair/Troubleshoot

Provides step-by-step instructions to access the Windows Command Prompt via bootable media for advanced system repair and troubleshooting.

Read More
Thinkpad P1 Gen 6: Sudden Thunderbolt 3 Dock USB-C Charging Stopped Working

Resolve sudden Thunderbolt 3 dock USB-C charging and internet failure on ThinkPad P1 Gen 6 by updating firmware, resetting the dock, and adjusting power settings.

Read More
ASUS Windows 11 Laptop: Internet Connection Issue with Hotspot

Resolve ASUS Windows 11 laptop spinning wheel issue when connecting to mobile hotspot by resetting network stack, disabling IPv6, and adjusting power settings.

Read More
Developing iOS Project with Firebase: Logging in and Sending Push Notifications

Integrates Firebase to enable secure user authentication and push notifications in iOS applications.

Read More
Troubleshooting Bash Script with Suspected Issues of Spaces, Dashes, Filenames and Quoting

Resolve Bash script failures caused by word splitting, globbing, and special characters in filenames by applying proper quoting techniques.

Read More
Populating OneDrive Folder for Local Backup without Affecting Remote Files

Prevent OneDrive from deleting remote files during Windows reinstallation by unlinking the account or using symbolic links to isolate local data.

Read More
Force First Frame as Keyframe Without Re-encoding: A Quick Solution

Resolve inaccurate seeking and playback glitches by re-encoding video to ensure the first frame is a valid keyframe.

Read More
Find Information in Database Using WSL (Ubuntu) on Windows-10

Resolve database connection issues from WSL Ubuntu on Windows 10 by configuring client tools and network access to query remote or local servers.

Read More
Configuring a New Router with Different Networks: One Family, One Guest

Resolve IP conflicts and isolate guest traffic by configuring a second router with a distinct subnet via its WAN port.

Read More
Quickly Open Multiple Stock Websites with a Single Command

Solve the problem of manually opening multiple stock research websites by creating a single command to launch them simultaneously on Windows, macOS, or Linux.

Read More
Improved Adobe Acrobat Search Experience: Access Advanced Search with Ease

Access advanced search filters like case sensitivity and regex in Adobe Acrobat by clicking More Options in the Find bar.

Read More
Port Forwarding VM via OpenVPN: A Comprehensive Guide

Configure OpenVPN server and iptables to forward specific ports from VPN clients to a virtual machine's internal IP address.

Read More
Understanding Partitions in the 1980s: A Look Back at MS-DOS and Master Boot Record

Explains how the Master Boot Record and partition table enabled MS-DOS to manage multiple disk volumes on a single physical drive.

Read More
Windows 10 Enterprise: Keyboard Not Detected in Managed Organization with Admin Privileges

Resolve Windows 10 Enterprise keyboard detection failures caused by Group Policy restrictions, driver corruption, or USB enumeration errors.

Read More
Can't Find x86_64 Versions of Applications on MacOS arm64 (M1)

Resolve missing x86_64 app issues on M1 Macs by installing Rosetta 2 and reinstalling apps as universal binaries.

Read More
How to Hide Installation Source for an Android App

Manage Android app installation source visibility by using USB transfers or file managers to reduce browser traces and isolate data via work profiles.

Read More
Connecting Momentus 4200.2 ST9808210A Hard Drive via USB Cable

Resolve inability to access Seagate Momentus 4200.2 ST9808210A hard drive by connecting it via USB using a compatible SATA-to-USB adapter and configuring the disk in Windows.

Read More