Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
VGSources
Blog

Django, Gunicorn and Nginx: Fixing Internal Server Errors After Restart

Find the real cause of Django 500 and Nginx 502 errors after a reboot by testing systemd, Gunicorn, the upstream socket, Nginx and Django production settings separately.
Length9 min Posted Quest giverVGSources Team

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A Django site that returns a 500 or 502 immediately after a reboot is usually failing at one layer of the deployment stack, not everywhere at once. Isolate the layers in order: systemd and Gunicorn startup, the Unix socket or TCP listener, Nginx’s upstream connection, and finally Django’s production settings. Check each locally before testing the public domain. This approach distinguishes an application exception from a dead service, a mismatched socket path, a permission problem, or a host-validation failure.

What a 500 or 502 means in this stack

The status code describes where the request failed. A 500 Internal Server Error is normally generated by Django or by application middleware after a request reaches Gunicorn. A 502 Bad Gateway is normally generated by Nginx when it cannot obtain a valid response from its configured upstream. Nginx may therefore show a 502 while Gunicorn records only worker-start messages. Gunicorn’s FAQ specifically warns that reverse proxies can return 502 responses while Gunicorn logs only new worker startups.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not assume that a running process proves a healthy deployment. Gunicorn can be running with the wrong working directory, an unusable virtual environment, an import failure in a worker, or a bind address that does not match Nginx. Conversely, Nginx can be healthy while it points at a socket that no process creates.

Start with a boot-specific incident snapshot

Capture evidence before restarting repeatedly. Repeated restarts can rotate away the first useful error and make a restart loop look like a new problem.

#1 Best Overall
Sale
Gaoye Blue Light Blocking Glasses
  • BLUE LIGHT BLOCKING GLASSES: Our blue light glasses for women boast UV400 protection, blocking harmful blue rays from computer screens. With these bluelight glasses women, you can enjoy gaming, reading, or watching TV with no worries of eye strain.
  • EYE RELIEF: Our blue light glasses are engineered to reduce blurry vision or strain caused by prolonged screen time. These womens blue light glasses aid in better sleep by preventing blue light from disrupting your natural sleep cycle, helping you fall asleep faster and enjoy a more restful night's sleep, making them the perfect christmas present.
  • COMFORTABLE: Crafted from durable material, our trendy blue light glasses for woman or blue light glasses men ensure long-lasting comfort. The high-transmittance lenses accessories, gamer gifts for men, help keep your eyes relaxed. Perfect stocking stuffers, gifts for gamers men, christmas gifts for men, halloween costumes.
  • LIGHTWEIGHT: These clear blue light glasses feature a lightweight frame, meaning they’ll stay comfy for long-term wear. Perfect as blue blockers glasses for women or mens blue light glasses, these non-prescription fake glasses for men can be worn throughout the day. The blue light blocking glasses women feature polycarbonate HD lenses, which are anti-reflective and restore true color.
  • WORRY-FREE PURCHASE: If you experience any issues, our support team is ready to assist you quickly. These are the perfect costume glasses for cosplay dressing up.
systemctl status gunicorn --no-pager
systemctl status nginx --no-pager
journalctl -u gunicorn -b --no-pager
journalctl -u nginx -b --no-pager
nginx -t

The -b option limits the journal query to the current boot, which is useful when the failure appeared after a reboot. Save the Nginx access log, Nginx error log, and Gunicorn output for the same time window. The access log tells you what status reached the client; the error log explains upstream connection failures, permission denials, timeouts, and configuration errors; the Gunicorn or systemd stream explains application startup and worker failures.

If nginx -t fails, do not reload Nginx. Correct the reported syntax or file-path error first. A successful test validates configuration syntax, not upstream availability, so continue with the socket and application checks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Verify the systemd unit before debugging Django

Read the unit systemd is actually using

Manual commands often run from a shell that has a different directory, environment, PATH, and user than systemd. Display the complete unit and its drop-ins:

systemctl cat gunicorn
systemctl show gunicorn -p User -p Group -p WorkingDirectory -p ExecStart -p Environment -p EnvironmentFile

Check these values against the deployed project:

  • WorkingDirectory: it must exist and contain the project package and management code expected by the WSGI import.
  • ExecStart: use the Gunicorn executable inside the intended virtual environment, not an accidentally selected system installation.
  • EnvironmentFile and Environment: confirm the settings module, secret key, database URL, and other required variables are present for the service.
  • User and Group: the account needs read and execute access to the application, virtual environment, and parent directories.
  • WSGI module: the module named after gunicorn must match the project’s actual WSGI entry point.

A service that was never enabled will not return after a reboot even if it worked when started manually:

systemctl is-enabled gunicorn
systemctl enable gunicorn
systemctl restart gunicorn
systemctl status gunicorn --no-pager

Use the unit’s journal output to identify an invalid directory, missing executable, import exception, or restart loop. Fix the unit rather than adding ad-hoc shell commands to the boot process.

Run Django and Gunicorn without Nginx

Test the application boundary independently. First activate the same virtual environment and use the same settings module and environment values as the unit. Then run Django’s checks:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Windex Gaming Cleaning Wipes, Pre-Moistened Wipes to Instantly Clean all Gaming Gear and Electronics, Resealable Packaging for a Freshness Lock, 25 count (Pack of 1)
  • WINDEX GAMING WIPES: effortlessly clean all your gaming gear and gaming electronics in one easy step with our new Windex Gaming Wipes
  • AMMONIA FREE: our ammonia-free formula is safe to use on all of your favorite gaming equipment like consoles, headsets, controllers, screens, keyboards, and more
  • PRE-MOISTENED WIPES: each wipe instantly removes dust, dirt, and stubborn smudges and fingerprints leaving a streak-free shine
  • ANTI-STATIC: great for cleaning and wiping down your gaming gear and electronics leaving behind no visible residue
  • COMPACT RESEALABLE PACKAGE: store your pack of Windex Gaming Wipes anywhere in your home for whenever a quick and easy wipedown is needed
cd /srv/myproject
. /srv/myproject/venv/bin/activate
python manage.py check --deploy

The path above is an example; use the paths shown by systemctl cat gunicorn. If the check reports a missing database, secret key, middleware, or security setting, resolve that before investigating proxy behavior.

For a temporary foreground test, stop the managed service or use a separate port, then start Gunicorn with the same WSGI module and working directory:

cd /srv/myproject
/srv/myproject/venv/bin/gunicorn --chdir /srv/myproject myproject.wsgi:application --bind 127.0.0.1:8001

From the server, request that listener directly:

curl -i -H 'Host: example.com' http://127.0.0.1:8001/

A direct 500 points to Django, middleware, a database, migrations, or an application import. A successful direct response shifts attention to Nginx’s upstream endpoint, socket permissions, or proxy headers. Stop the foreground process and return to the systemd-managed service after the test; do not leave an unmanaged production process competing for the same socket or port.

Make Nginx and Gunicorn use the identical upstream

Compare Nginx’s proxy_pass with Gunicorn’s --bind or a socket unit’s ListenStream. The endpoint type, path, and name must match exactly. A process can be healthy while Nginx reports “no such file” simply because one side uses /run/gunicorn.sock and the other creates a socket inside the project directory.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Gunicorn or systemd endpoint Matching Nginx form Typical mismatch symptom
127.0.0.1:8001 proxy_pass http://127.0.0.1:8001; Connection refused if Gunicorn is stopped or bound to another port
/run/gunicorn.sock proxy_pass http://unix:/run/gunicorn.sock; No such file or permission denied when the path or access differs
/srv/myproject/gunicorn.sock The same full path in proxy_pass 502 when Nginx still points to an old socket location

Inspect the live listener and socket:

ss -ltnp
sudo find /run /srv/myproject -maxdepth 2 -name 'gunicorn.sock' -ls
stat /run/gunicorn.sock

Do not infer the Nginx account. Distribution defaults may be www-data, nginx, or another configured identity. Find the account in the local Nginx service and configuration, then test the endpoint as that account. For a Unix socket, a connectivity test can be run with a shell launched as the Nginx user:

sudo -u www-data curl --unix-socket /run/gunicorn.sock -i http://localhost/

Replace www-data with the account used by your installation. If this test fails, changing Django code will not fix the proxy path.

Rank #3
Sale
LISEN Cell Phone Stand Phone Holder for Desk, Office Decor Gadgets for Men
  • Ergonomic & Adjustable Design: Fight "text neck" and improve your posture. Designed for comfort, it offers an adjustable height (7.1in-8.5in) (1.4in adjustable range) and angle (5°-85°) Please note: cell phone stand is only 9 inches tall—the length of a standard pencil
  • Without blocking subtitles Perfect for office desk Tiktok Face Time Zoom video—this is the ultimate kitchen desk essential for phones! Perfect viewing experience while reducing neck back strain, A must-have for gamers streamers desk, and anyone who values both style and support!
  • Sleek & Stable Design fits Otterbox Case: Say goodbye to bent cables, tangles, and tip-overs! LISEN’s stylish adjustable desk phone holder features a built-in charging hole and smart cable management, keeping your phone secure and your workspace clutter-free cool gadgets for men
  • ANTI-SLIP DESIGN free hands: The under 10.00 items easy gadgets back and the bottom of this kitchen essentials for women are fully covered by anti-skid silicone, which LISEN stand up desk decor can provide maximum protection device from any scratches and slides
  • Your Perfect Viewing Companion:If your product arrives damaged or breaks within 365 days, reach out to LISEN for a quick and hassle-free solution. Struggling with assembly, like tightening the screw? We’ve got your back! Your experience matters to us. (Product including: phone Holder stand*1, screw*1, hexagon screwdriver*1, specification*1)

Repair Unix-socket ownership and traversal safely

“Permission denied” can refer to the socket itself or to any parent directory. Inspect every component:

namei -l /run/gunicorn.sock
stat -c '%A %U %G %n' /run /run/gunicorn.sock

The Nginx account needs permission to traverse each parent directory and to read and write the socket as required by the proxy connection. Set these properties in systemd so they survive a reboot; do not rely on a one-time chmod that disappears when the socket is recreated.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Socket-activation pattern

Gunicorn documents a socket-activation arrangement with a socket unit and a service unit. A representative socket unit is:

[Unit]
Description=Gunicorn socket

[Socket]
ListenStream=/run/gunicorn.sock
SocketUser=django
SocketGroup=www-data
SocketMode=0660

[Install]
WantedBy=sockets.target

The paired service should require the socket and start Gunicorn with the same endpoint:

[Unit]
Description=Gunicorn application server
Requires=gunicorn.socket
After=network.target

[Service]
User=django
Group=django
WorkingDirectory=/srv/myproject
ExecStart=/srv/myproject/venv/bin/gunicorn myproject.wsgi:application

[Install]
WantedBy=multi-user.target

Use the actual service names and account policy for your host. Enable the socket so it is recreated at boot:

systemctl daemon-reload
systemctl enable --now gunicorn.socket
systemctl enable gunicorn.service
systemctl status gunicorn.socket gunicorn.service --no-pager

Keep the application service account separate from the web-server identity where practical. Grant only the socket group and mode needed for Nginx; do not run Django as the Nginx user merely to bypass a permission error.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Ledagic IC+RGBW USB Powered Led Light Bar with App & Remote Control, 2 Pack
  • Easy Installation: Our gaming lights have been designed to enhance your entertainment experience. Simply position the led light bar next to your TV or game console to create a game room environment with ease. They come with USB power and a 60 inch cord for direct mounting and mobility
  • Audio Syncing & Extensive Mode: The built-in high-sensitivity music sensor allows you to sync the TV led lights to your favorite music. Lights react and move to the beat of music, film and game audio, creating an incredible immersive sound and light experience – and all without the need for an additional hub. You can choose from 64+ patterns, including strobe, illusion, jump, energy, gradient, running, chasing, fluttering mode etc. Each mode can be applied to different scenes
  • 64+ Chasing IC+RGB & W Effect: The independent control design of IC+RGB and white all-in-one multifunctional rgbw led bar lights monitor backlight allows you to easily switch the led lights for desk between IC+RGB and white to enjoy a variety of lighting effects, you can choose white lighting mode with high brightness for better illumination when working, etc. Choose IC+RGB lighting mode when you need to create an entertaining atmosphere for the light show, 16 million colours of Color changing rgb light bar let you dance to the beat and create a dynamic party atmosphere
  • Dynamic and Dimmable Lights: 1%-full brightness free brightness adjustment gives you the flexibility to adjust dimmable led light bar for room decorations or a variety of occasions
  • USB Powered: USB light bars for room can be powered by powernank, usb charger, TV, Monitor, laptop PC mainframe, making behind TV led lighting bar easy to install in any location.TV led lights are powered by the TV usb interface / PC mainframe, can be turned on/off synchronously with TV / PC

Read each log for the question it answers

Nginx error and access logs

The error log reveals upstream connection refusal, a missing Unix-socket file, permission denial, timeout, and configuration errors. The access log records the request, status, and often the upstream timing, allowing you to correlate a browser’s 502 with a precise server-side event. If the default path is unknown, inspect the compiled Nginx options:

nginx -V 2>&1 | tr ' ' 'n' | grep error-log-path

Also inspect included configuration files for an explicit error_log or access_log directive.

Gunicorn output

Gunicorn may send errors to stderr, the journal, or a configured file. Its selected error-log path must be writable by the worker process. If the file is empty, check the unit’s standard-output and standard-error settings and read the journal rather than assuming the application is healthy.

systemd journal

The journal is the authoritative place for unit start failures, environment-file errors, invalid working directories, executable permission errors, and restart loops. Correlate timestamps across systemd, Gunicorn, and Nginx before changing settings. A single timestamp often shows whether Nginx attempted a request before Gunicorn had finished starting.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Validate Django’s production configuration

ALLOWED_HOSTS and host headers

With DEBUG = False, Django requires a suitable ALLOWED_HOSTS value. A request made through a newly configured domain, public IP, or proxy host can therefore reach Django and still fail host validation. Django raises SuspiciousOperation when the incoming Host does not match an allowed value.

ALLOWED_HOSTS = ["example.com", "www.example.com"]

Use the real names clients send, including a separate entry when both the apex domain and www hostname are in use. Do not enable DEBUG in production to reveal an exception; that can expose secrets and internal details. Instead, run:

Best Value
Sale
HUANUO FlowLift™ Dual Monitor Stand, Fully Adjustable Gaming Monitor Desk Mount for 13–32″ Computer Screens, Full Motion VESA 75x75/100x100 with C-Clamp & Grommet Base, Each Arm Holds 4.4 to 19.8 lbs
  • Compatible with Wide Screens - To ensure compatibility with the dual monitor mount, your each monitor must meet three conditions at the same time: First, computer screens size range: 13 to 32 inches. Second, screen weight range: 4.4 to 19.8 lbs. Third, the back of the monitor screen must have VESA mounting holes with a pitch of 75x75mm or 100x100mm.
  • Regarding the compatibility with desks - Your desk must meet three conditions at the same time: First, desk material: Only wooden desks are recommended, plastic or glass desks cannot be used. Second, desk thickness range: 0.59" - 3.54". Third, the bottom of the desk should not have any cross beams or panels, as this will interfere with installation. We recommend carefully checking that your desk and monitors meets all above conditions before purchasing.
  • Dual C-Clamp Hold - Worried your dual monitors might wobble or slip? Our upgraded base uses a larger platform plus a dual C-clamp structure to lock the dual monitor arm firmly to your desk. Each arm safely keeps your screens steady while you type, click and game—no shaking, no sliding, just a clean and secure setup you can trust every day. It also provides Grommet Mounting installation choice, both options ensure stable and secure fixation for your 0.59" - 3.54" desk.
  • Full-Motion Adjustment For Comfortable View - Pull the screen closer when you’re deep in a spreadsheet, push it back to watch videos, or rotate to portrait for coding — moving everything smoothly with just one hand. The monitor stand offers +85°/-50° tilt, ±90° swivel and 360° rotation. Raise your monitor up to 15.75″ to support a healthy sitting posture. Whether you’re working from home, gaming through the night, or switching between video calls and documents, getting the screens to your natural line of sight helps relieve neck, shoulder and back strain so you can stay focused longer with less fatigue.
  • Keep Your Desk Organized: By lifting both screens off the desktop, this dual monitor stand opens up valuable space for your keyboard, notebook, docking station or a simple, clutter-free work area. Built-in cable management guides wires along the arms, keeping cords out of sight and out of the way. Enjoy a tidy, modern workstation that looks as good as it feels to use.
python manage.py check --deploy

Run it with the same production settings module and environment variables loaded by systemd. Confirm the secret key is present, the database credentials are available, the database accepts connections, and migrations are applied. A manual shell test that loads a developer environment does not validate the service environment.

Database and migration failures

A reboot can change DNS availability, mount timing, credentials, or service ordering. If Gunicorn starts but every request returns 500, inspect the traceback for database connection and missing-table errors. Verify the database service is available, then apply migrations using the production settings:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
python manage.py migrate --plan
python manage.py migrate

Only run migrations after confirming that the release and database backup policy permit them. The key diagnostic is whether the same command succeeds under the service’s environment and account.

Keep static and media failures separate from upstream failures

Dynamic requests and static assets follow different paths. In production, define STATIC_ROOT and collect the files so Nginx can serve them directly:

python manage.py collectstatic --noinput

Configure an Nginx location for that directory and verify its filesystem permissions independently. Missing CSS, JavaScript, or images with a healthy HTML response is a static-file problem, not evidence that Gunicorn is returning 502.

Uploaded media is untrusted. Serve it from a controlled media location and ensure the web server cannot execute uploaded files. A media permission change must not grant write access to the application code or virtual environment.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use a dependency-aware recovery sequence

  1. Capture systemctl status, current-boot journals for Gunicorn and Nginx, Nginx access and error logs, and Gunicorn output.
  2. Run nginx -t; reload Nginx only after syntax passes.
  3. Inspect the Gunicorn unit’s executable, working directory, WSGI module, user, environment, and bind address.
  4. Confirm that the Unix socket or TCP listener exists and responds when tested as the Nginx account.
  5. Make Nginx’s proxy_pass exactly match Gunicorn’s --bind or the socket unit’s ListenStream.
  6. Set socket owner, group, mode, and parent-directory traversal in the unit configuration.
  7. Run Django’s deployment check and verify ALLOWED_HOSTS, secret key, database connectivity, migrations, and static files.
  8. Restart or reload in dependency order, then test the local listener, the Unix socket if applicable, and the public URL.
  9. Enable the socket or service and Nginx at boot, and document paths, accounts, and settings so the next restart is reproducible.

After each change, test one boundary only: Django/Gunicorn directly, then the socket or TCP endpoint, then Nginx locally, and finally the public hostname. This prevents a successful browser refresh from hiding which correction actually worked.

Choose durable fixes instead of reboot-time workarounds

Decision axis Durable choice Risky workaround
Persistence across reboot Enabled systemd service or socket with explicit dependencies Starting Gunicorn manually from a shell
Endpoint One documented Unix socket or localhost TCP port used by both services Changing only Nginx or only Gunicorn until the error disappears
Privilege separation Dedicated application user and controlled socket group/mode Running Django as Nginx or making broad directories writable
Observability Journal plus Nginx and Gunicorn logs with correlated timestamps Relying on a browser’s generic 500 page
Operational risk Correct unit, settings, and permissions Temporary chmod changes or enabling DEBUG in production

The most reliable repair is the one that remains correct when the machine boots without an administrator logged in: explicit paths, explicit users, an enabled dependency chain, validated production settings, and logs that identify the failing boundary.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More quests from Patch Notes

  1. How to Set Up a RedM (RDR2) Server in 2026: License Key, txAdmin and server.cfg, Step by StepBlog11min
  2. Best RedM (RDR2) Server Hosting in 2026: Comparing Four Hosts on Slots, Memory and PriceBlog10min
  3. How to Host a Mindustry Server in 2026: server-release.jar, Port 6567 and the Commands That MatterBlog7min
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.