Chapter 11: Application Hosting — WordPress, Flask and Express
11.2 Flask application with Gunicorn + Nginx
If your example calls app.run(), it starts Flask’s development server. For a deployment, identify the WSGI application, use an appropriate server or platform, and verify how the intended public path reaches it.
तुमच्या उदाहरणात app.run() असेल तर तो Flask चा development server सुरू करतो. Deployment साठी योग्य WSGI server किंवा platform निवडा. ठरलेला सार्वजनिक URL त्याच app पर्यंत पोहोचतो का ते तपासा.
अगर उदाहरण में app.run() है, तो Flask का development server शुरू होता है. Deployment के लिए सही WSGI server या platform चुनो. यह जाँचो कि तय सार्वजनिक URL सही app तक पहुँचता है.
Why Gunicorn?
Friends, app.run() is only for development on your laptop. In production, Gunicorn runs several workers and Nginx stands in front.
मित्रांनो, app.run() हा फक्त तुमच्या लॅपटॉपवर डेव्हलपमेंटसाठी आहे. प्रॉडक्शनमध्ये Gunicorn अनेक वर्कर्स चालवतो आणि Nginx समोर उभा राहतो.
दोस्तों, app.run() सिर्फ़ आपके लैपटॉप पर डेवलपमेंट के लिए है. प्रोडक्शन में Gunicorn कई वर्कर्स चलाता है और Nginx आगे खड़ा रहता है.
flask run / app.run() starts a development server for local testing. It is not designed to provide production security, stability or performance. Gunicorn ("Green Unicorn") is a production WSGI server that runs several worker processes of your app. Nginx sits in front to handle clients, static files and TLS.
Client ─► Nginx :80 ─┬─ /static/* → served directly from /opt/flaskdemo/static
└─ everything else → proxy_pass http://127.0.0.1:8000
│
Gunicorn master (systemd service)
├── worker 1 (Flask app)
├── worker 2
└── worker 3
Step 1 — Project structure
/opt/flaskdemo
├── app.py # Flask application
├── wsgi.py # entry point for Gunicorn
├── requirements.txt
├── templates/
│ └── index.html
├── static/
│ └── style.css
└── venv/ # virtual environment (not committed to Git)
Step 2 — Install and create the app
Use a dedicated candidate directory and a supported Python interpreter. Create a virtual environment for that release and install its reviewed dependencies into that environment. The local demonstration below provides a complete small app and uses pinned direct dependencies for its replay.
Stage the intended source revision and reviewed dependency set in a candidate directory. Verify the Python interpreter and package environment that will actually serve requests.
Step 3 — Test Gunicorn manually
On a dedicated practice host, start Gunicorn with the intended module, virtual environment and private listener. Use a bounded named route check, confirm the expected response marker, and stop only the process started for the rehearsal. The local lab below exercises this sequence on its own socket.
wsgi:app names an importable module and an application object. A factory can be invoked with a target such as dispatch:create_app(). Choose worker type and count based on the app and measurements, using CPU-based rules only as starting heuristics.
Step 4 — systemd service
Read this example as a unit for a host where the service identity, release path, app module and private port have already been approved. The environment line is a non-secret example marker. Adapt the account and settings for the actual deployment, validate the candidate unit, and only apply it to the intended service.
[Unit]
Description=Gunicorn for the dairy pickup application
[Service]
Type=exec
User=dairy-app
Group=dairy-app
WorkingDirectory=/opt/dairy-flask/current
Environment=DAIRY_LAB_RELEASE=example-release
ExecStart=/opt/dairy-flask/current/.venv/bin/gunicorn --workers 2 --bind 127.0.0.1:18000 --access-logfile - dispatch:create_app()
Restart=on-failure
[Install]
WantedBy=multi-user.targetStep 5 — Nginx configuration
This Nginx excerpt is for a private test listener on a host with both example ports available. It illustrates a single proxy setting the scheme it directly sees and the immediate client address. A production deployment must match the actual TLS termination and trusted proxy chain. Verify the intended candidate configuration without disabling unrelated hosts.
server {
listen 127.0.0.1:18080;
server_name pickup.dairy.example.test;
location /static/ {
alias /opt/dairy-flask/current/static/;
}
location / {
proxy_pass http://127.0.0.1:18000;
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $remote_addr;
}
}SELinux. Where active, inspect any denial for the intended Web-to-Gunicorn connection or static path. Apply the actual required policy in coordination with the authorized host owner.
Use the scoped named candidate hostname for the route test. Confirm an expected dynamic response and a readable test asset if that service intentionally serves static files. Verify the normal public HTTPS route separately when it is approved.
Ravindra Bagale's Tip
Keep the source under version control and build a candidate from a known revision and dependency set. Rehearse return to a compatible prior release. An older source checkout alone cannot restore the prior runtime, configuration or data.
Ravindra Bagale's Tip – मराठी
Code Git मध्ये ठेवा आणि ठरलेल्या revision व dependencies वरून candidate तयार करा. मागच्या सुसंगत release वर कसं परत जायचं याचा सराव करा. फक्त code checkout केल्याने जुने runtime, configuration किंवा data परत येत नाहीत.
Ravindra Bagale's Tip – हिंदी
Code Git में रखो और तय revision व dependencies से candidate बनाओ. पिछले compatible release पर लौटने का अभ्यास करो. केवल code checkout करने से पुराना runtime, configuration या data वापस नहीं आता.
Step 6 — Updating the application
Stage and verify the intended release in its own environment. Apply the approved service change and inspect matching startup evidence. Check both the private app route and the public named route. Keep the previous compatible release and validate its return procedure before relying on it.
Ravindra Bagale's Tip
Many students mix up app:app and wsgi:app in Gunicorn and get ModuleNotFoundError in journalctl. wsgi:app means the file wsgi.py and the app object inside it. If the service fails, first look at journalctl -u flaskdemo -n 50 --no-pager.
Ravindra Bagale's Tip – मराठी
खूप students Gunicorn मध्ये app:app आणि wsgi:app मध्ये गोंधळतात, आणि journalctl मध्ये ModuleNotFoundError येतं. wsgi:app म्हणजे wsgi.py file आणि त्यातला app object. Service fail झाली तर आधी journalctl -u flaskdemo -n 50 --no-pager बघा.
Ravindra Bagale's Tip – हिंदी
बहुत students Gunicorn में app:app और wsgi:app में उलझ जाते हैं, और journalctl में ModuleNotFoundError आता है. wsgi:app मतलब wsgi.py file और उसके अंदर का app object. Service fail हो तो पहले journalctl -u flaskdemo -n 50 --no-pager देखो.
Lab
Run the local Flask and Gunicorn exercise below. Observe the exact JSON response, a controlled 404, and a replacement worker under the same master. The lab starts no public web service and removes its temporary socket.
Got it? Gunicorn runs the code, Nginx stands in front, and systemd can restart it according to the unit’s restart policy. Now let's move on to Express.
समजलं का? Gunicorn app चे workers सांभाळतो, Nginx समोरची request योग्य ठिकाणी पाठवतो आणि systemd च्या restart policy नुसार service पुन्हा सुरू होऊ शकते. आता Express बघूया.
समझ आया? Gunicorn app के workers संभालता है, Nginx request सही जगह भेजता है और systemd की restart policy के अनुसार service फिर शुरू हो सकती है. अब Express देखते हैं.
Keep a small Python service available after the terminal closes
Mauli Dairy’s pickup team wants to look up opening hours by collection point. The developer runs a Flask application on a laptop, opens the east pickup page and sees the correct time. Later the person running the program closes their terminal, and the application disappears. The code works while a developer runs it. Hosting asks for a repeatable way to start it, connect normal requests to it, observe a problem, and decide how to recover.
Flask supplies the Python application code and routing tools. When a request asks for a known path, Flask helps map it to a Python function and convert the returned data into a web response. Gunicorn is a WSGI server that can load a Flask application and manage worker processes. Nginx can sit at the public-facing side and pass applicable requests to Gunicorn. A system service manager such as systemd can start and supervise the overall Gunicorn process on a configured Linux host. These jobs have different evidence and different failure modes.
Use one small behavior to follow the layers. The rider asks /pickup/east and expects an opening time of 16:00. A request for a branch that does not exist should get a controlled 404. A readiness check can confirm the process loaded the current release. In production, check whether readiness also needs a relevant dependency. Keep the business outcome, process status and environment assumptions separate when you test.
Flask’s built-in development server and debugger are useful for local development. Use an appropriate production WSGI server or hosting platform for deployment. The shell command python app.py does whatever that particular file contains. In many beginner examples it invokes the development server; the filename itself does not define a production service. The question is what runtime actually handles the web request and how it is managed.
Read the request path and the WSGI entry point
A request begins with an advertised HTTPS hostname and path. Public DNS and TLS need to get the visitor to the correct entry point. Nginx can terminate HTTPS for a directly hosted site or sit behind another approved frontend. Its configuration chooses a route or serves a static file. For the pickup API, the reverse proxy sends the request to Gunicorn on the private network path or Unix socket identified by the site configuration. A reverse proxy is a server that talks to a backend on behalf of the incoming client.
WSGI stands for Web Server Gateway Interface. It defines a standard way for a Python web server and a compatible Python application to exchange a request and response. Gunicorn receives and handles an HTTP connection, prepares the data passed to the WSGI application, then uses the application’s response. Flask registers the pickup route and decides what JSON, status and headers to return. Flask should not have to implement the details of accepting every raw network connection itself.
A Gunicorn target such as dispatch:create_app() identifies a Python module called dispatch and a factory function to call. A factory is a function that creates an application object. The import target wsgi:app instead asks for the variable app in the module wsgi. The choice depends on the actual project. A module can be a file or a package available to the selected Python environment. Confirm that the specified object is the application you intend to serve.
Check the current directory and interpreter when imports fail. In a development terminal, you might run from a project root with a virtual environment already activated. In a service the working directory and full interpreter paths come from its configuration. If the module imported successfully in your terminal and fails in the service, compare those two environments before rewriting the application. A missing third-party library and an incorrect import target can both produce an import error, with different fixes.
Draw the sequence in four boxes labelled public frontend, private listener, Flask route and useful response. Under the first write the exact Host and TLS identity. Under the next write the Gunicorn socket or address and port. Under the Flask route write the expected method and path. Under useful response write the status and body marker. This drawing helps when one team tells you the web server is up while another says the API returns the wrong result.
Keep an application release and its dependencies reproducible
A virtual environment is a project-specific Python environment. It lets the checkout have its own dependencies without replacing Python libraries another application needs. Record the Python version, the application release, how its dependencies are resolved, and which environment serves the process. The Python interpreter used by the system package manager may differ from the interpreter the deployment runs. Current versions supported by the selected Flask and Gunicorn releases should guide that choice.
Use the same interpreter for installation and execution when building a candidate. Calling the selected interpreter with -m pip makes the relationship clear. A package list generated with pip freeze describes what is installed in that environment. A release workflow needs a reviewed and reproducible dependency selection with a procedure for maintaining updates. Installing unpinned latest dependencies directly into the live release can change behavior during a routine re-run. An exact classroom package version is a reproducible example, not a substitute for current production patch review.
Choose how the application receives configuration. The lab adds a harmless release marker through its process environment, which lets the application identify the version during tests. An actual service may need a database connection, a signing key and other sensitive values. Use an approved credential mechanism and restrict which process can access it. Keep secrets out of app templates, source control, process arguments and logs. A missing setting should fail or degrade predictably without printing the secret alongside the error.
Place persistent application data apart from disposable worker processes and code releases. A worker can be replaced when it exits. If the only copy of a booking is stored in a Python dictionary in that worker, the booking can disappear. With several workers, another worker may not even share that dictionary. Use deliberate durable storage for business state, and choose appropriate shared session and data mechanisms where the product needs them.
Observe a candidate against a release marker you chose before the test. “Gunicorn restarts cleanly” answers a process lifecycle question. “The public pickup route serves the correct current schedule and the old URL returns the intended result” answers a customer behavior question. Add a representative operation and control paths before promoting a candidate. Changing the working directory, virtual environment, app version and proxy target together makes it harder to tell which change produced the result.
Understand what the Gunicorn master and worker processes do
Think of two responsibilities inside Gunicorn. A supervising process, called the arbiter or master, manages worker processes. The workers handle individual requests according to the selected worker type. In a simple synchronous setup, one worker handles one request at a time. Several worker processes can handle independent requests and can be replaced individually. Configuration for threads or asynchronous work changes the concurrency model. The pilot exercise intentionally uses one synchronous worker so a worker replacement is easy to observe.
You may encounter a formula that multiplies the CPU count to suggest a starting worker count. It is a starting hypothesis, not a minimum requirement. More processes can use more memory or open more database connections. A single CPU-bound request can consume capacity differently from a route that mostly waits for another system. Choose a worker type and count using measurements of latency, memory, useful completion rate, timeouts and dependency capacity for your workload.
For the dairy, compare a lightweight schedule lookup to a report generating a large set of records. The schedule request might finish while another worker handles the report. Increasing workers can help only if the workload and shared dependencies can support it. If every new worker submits the same expensive database query, the database may become the limit. Treat the worker count as an operating choice and record the behavior before and after changing it.
Gunicorn can replace a worker that exits while the master stays running. The service manager supervises a different layer and can start a new Gunicorn master when the configured policy applies. Neither tells you that the app silently preserved every request in flight or that startup will always succeed. A process can repeatedly fail to import a module. A restart limit can stop repeat attempts. Inspect the actual running behavior and logs before calling the service healthy.
Keep the public and private parts of Nginx routing explicit
Choose a private backend interface for Gunicorn. On one machine it can listen on a Unix socket or a loopback address. Loopback routes only within that machine, and an appropriately protected Unix socket can apply local filesystem access rules. On separate hosts, the private connectivity needs its own allowed sources, port and deployment requirements. Do not expose Gunicorn directly just because the Nginx path is missing or misconfigured. The intended frontend can handle TLS, approved limits and routing.
Use an exact named frontend route and a deliberate proxy_pass mapping. Changing whether a URI appears in Nginx’s upstream mapping can change the path sent to the application. A public route under a prefix such as /dairy/ may reach Flask with or without that prefix depending on the chosen configuration. Align frontend routing and Flask’s expected rule, then test the path Flask actually receives. A local upstream request alone does not establish what the public mapping will do.
A proxy can pass information about the original request’s scheme or client address. Flask sees the connection from its immediate frontend, so it needs a controlled way to interpret values that should reflect the original route. Only trust the number of hops and individual headers known for this deployed chain. Werkzeug’s ProxyFix middleware can interpret configured forwarded headers. Gunicorn also has settings governing forwarded scheme information. Decide which layers supply and consume which values. A client-supplied value alone is not evidence of the real scheme or address.
For example, if Nginx is the single trusted HTTPS endpoint and the application needs to generate absolute callback URLs, make sure the approved Nginx route supplies the scheme it actually observed. The backend should be inaccessible to arbitrary clients that could bypass the intended proxy. In an architecture with a load balancer in front of Nginx, Nginx’s immediate connection can use HTTP even though the original visitor used HTTPS. Passing the observed local scheme blindly in that case can erase useful earlier information. Work out the boundary using the exact trusted path.
Static files deserve their own small scope. Nginx can serve approved CSS and assets from a release directory without sending the request through Flask. That can improve efficiency, but the route needs to point at those specific public files and match them to the current app release. Never serve the entire project or virtual environment from a static mapping. Test a known style file and a nonexistent file alongside the API route. A styled home page can continue working even when the API process failed.
Describe the service unit before applying it
A systemd unit defines how a Linux service is started and managed. Write down the service name, its dedicated operating-system identity, working directory and exact executable and arguments. The application process should run with the rights needed by that service. Avoid running it as root merely to use a public port. The frontend can manage public listening separately. If the service uses temporary sockets or files, agree which process creates them, which group can read or connect, and how they are removed.
Choose a restart policy and acknowledge what it can observe. Restart=on-failure can restart a service after qualifying failures subject to systemd policy and limits. It does not guarantee a healthy public route. If a programmer intentionally stops the service, that is a different action from an unexpected crash. If the process fails repeatedly on a bad app import, the restart loop should not be your release plan. Find the cause in logs and verify a working candidate before posting a restart.
Enable and start are separate service operations. Enabling an applicable unit configures startup relationships for future activation. Starting it attempts to run it now. A service can be enabled but not currently serving traffic. After a unit file changes, its manager may need to re-read unit definitions before applying the new configuration. These operations change a specific supervised service and should be planned for the approved host and unit. In the lab there is no systemd unit and no edit to global settings.
Keep failure tests small. First ask which process the service manager owns. Then test whether Gunicorn has bound its intended private socket and loaded the expected app. Next send a named request through the frontend. Look at the service’s relevant logs, time, exact request and response. A failure observed before the proxy can talk to the backend cannot be explained by the Flask route alone. A valid 404 from Flask can instead prove that the backend handled a request and did not find that route.
Observe a real Flask worker being replaced
This local lab uses a Linux or macOS shell, a compatible Python interpreter with the venv module, and curl with Unix-socket support. The tested interpreter was Python 3.12 with Flask 3.1.3 and Gunicorn 27.0.1. Gunicorn runs on Unix-like environments, including an appropriate WSL setup. Package installation inside the new virtual environment may need the approved package index. It does not change system Python or a deployed site.
Predict the results before running the block. The east pickup route should return the schedule with status 200. A request for west should receive a deliberate 404. When the one worker exits, the Gunicorn master should replace it under the same local service. The result after replacement should still use the expected release marker. The app includes process identity in a private test response so the exercise can confirm it owns the specific child before requesting its stop. Do not expose this classroom route with process details on a real public service.
The exercise binds a private socket in the unique temporary directory. Curl supplies the socket explicitly, so the reserved hostname does not require DNS. The user-facing TLS frontend and process manager stay outside this particular test. Its purpose is to isolate the application import, a concrete route and a worker lifecycle. Save the output lines and describe what extra observations would be required to verify a public deployment.
(
set -eu
umask 077
lab=$(mktemp -d /tmp/flask-worker.XXXXXX)
trap 'rm -rf -- "$lab"' EXIT
python3 -m venv "$lab/.venv"
"$lab/.venv/bin/python" -m pip install --disable-pip-version-check \
Flask==3.1.3 gunicorn==27.0.1
cat > "$lab/dispatch.py" <<'PY'
import os
from flask import Flask, jsonify
def create_app():
app = Flask(__name__)
release = os.environ["DAIRY_LAB_RELEASE"]
@app.get("/ready")
def ready():
return jsonify(release=release, worker=os.getpid(), parent=os.getppid())
@app.get("/pickup/<code>")
def pickup(code):
if code != "east":
return jsonify(error="unknown pickup"), 404
return jsonify(hub=code, opens="16:00", release=release)
return app
PY
"$lab/.venv/bin/python" - "$lab" <<'PY'
import json
import os
from pathlib import Path
import signal
import subprocess
import sys
import time
lab = Path(sys.argv[1])
sock = lab / "flask.sock"
env = {name: value for name, value in os.environ.items()
if name != "GUNICORN_CMD_ARGS"}
env["DAIRY_LAB_RELEASE"] = "training-v1"
def request(route):
result = subprocess.run(
["curl", "-q", "-sS", "--max-time", "2", "--noproxy", "*",
"--unix-socket", str(sock), "--write-out", "\n%{http_code}",
"http://dairy.example.test" + route],
capture_output=True, text=True, check=True, timeout=3,
)
body, status = result.stdout.rsplit("\n", 1)
return int(status), json.loads(body)
def wait_for_worker(proc, previous=None):
until = time.monotonic() + 10
while time.monotonic() < until and proc.poll() is None:
try:
status, body = request("/ready")
if status == 200 and body["parent"] == proc.pid and body["worker"] != previous:
return body
except (subprocess.CalledProcessError, subprocess.TimeoutExpired):
pass
time.sleep(0.1)
raise RuntimeError("No expected worker became ready. Read gunicorn.log.")
args = [str(lab / ".venv/bin/gunicorn"), "--workers", "1", "--bind",
"unix:" + str(sock),
"--access-logfile", "-", "dispatch:create_app()"]
with (lab / "gunicorn.log").open("w+") as log:
proc = subprocess.Popen(
args, cwd=lab, env=env, stdout=log, stderr=subprocess.STDOUT,
start_new_session=True,
)
try:
first = wait_for_worker(proc)
assert first["release"] == "training-v1"
assert request("/pickup/east") == (
200, {"hub": "east", "opens": "16:00", "release": "training-v1"}
)
assert request("/pickup/west") == (404, {"error": "unknown pickup"})
# Stop only this fixture's verified child. Gunicorn should replace it.
os.kill(first["worker"], signal.SIGTERM)
second = wait_for_worker(proc, previous=first["worker"])
assert second["release"] == first["release"]
assert request("/pickup/east")[0] == 200
print("East: expected schedule. West: controlled 404.")
print("Worker replaced under the same Gunicorn master.")
except Exception:
log.seek(0)
print(log.read(), file=sys.stderr)
raise
finally:
if proc.poll() is None:
proc.terminate()
try:
proc.wait(timeout=8)
except subprocess.TimeoutExpired:
os.killpg(proc.pid, signal.SIGKILL)
proc.wait(timeout=5)
assert proc.poll() is not None and not sock.exists()
print("Temporary Gunicorn process and Unix socket closed.")
PY
)
The shell creates a virtual environment and installs the lesson’s packages into it. The project consists of one Python module whose factory creates the site. The Python harness starts Gunicorn using that environment, the project’s working directory and the chosen process setting. It polls the intended private route with a bounded time limit. This is more specific than sleeping a fixed number of seconds and assuming whatever responds belongs to this run.
Read the named result for each route. The east response contains an opening time and a release marker. A valid HTTP 404 for west is an expected application outcome, so the curl command checks the status without treating every non-200 as a transfer failure. The parent process ID check ties the first worker to the Gunicorn master the harness started. After the lab sends a scoped termination signal to that child, it waits for a distinct worker under the same master to return the original release.
Notice what the result says about availability. The operation passes again after replacement. The exercise says nothing about whether a real request in progress at the time would complete or whether there would be a gap with one worker. A production release with availability requirements may need additional worker capacity, graceful drain behavior and evidence from requests during a transition. Keep measured business behavior separate from the simple fact that a new PID appeared.
If a setup step fails, read the stage. A package index failure occurred before the app started. A startup or import error prints the Gunicorn log while the scratch directory still exists. A real HTTP 404 with an expected payload means the application handled the route. A connection failure to the socket points to a different stage. On normal completion the harness shuts down its own process and checks the socket is gone. The shell trap removes its temporary directory. No other process or listening port is used.
Take a candidate through verification and a scoped return
On a shared server, record the application release, its virtual environment, the service configuration and the exact Nginx route in scope. Take the before-state evidence before changing anything. The route serving another internal site might share the same public service or default listener. Keep its configuration and traffic out of the change. A syntax check is valuable because a mistake in a shared web configuration can prevent an otherwise unrelated reload from succeeding.
Prepare a candidate environment linked to a known source revision and dependency selection. Test direct private application responses first, then test the intended named frontend. Let one concrete test prove the current opening time for east pickup and another prove the deliberate unknown-route outcome. Add a static asset check if Nginx serves it. Include the configured release marker for the application and avoid building acceptance entirely from a worker count or service state.
Before using a real database, verify expected schema and compatible data between the candidate and earlier release. A code rollback can be as simple as referring to the same previous deployment artifact when no incompatible changes occurred and the operator knows the intended process. A checkout of older code alone does not restore changed dependencies, configuration or database state. Define what record the current service must keep even if the rollout fails. Verify a compatible return path rather than promising an instant rollback for every case.
Logs have a useful order in this design. The Nginx access log shows the named request and status. Its error log can indicate a connection failure to the private upstream. Gunicorn startup and worker logs show whether the application imports and the intended processes launch. Flask operation logs can explain a route decision or failed dependency. Logs can contain account or request data, so only capture sanitized pieces relevant to the specific incident. Finding a time-matched old error does not establish that the new release still exhibits it.
When the frontend gives 502, compare the configured socket or address against Gunicorn’s actual listener. Check permissions or network source before touching application code. When Flask gives 404, inspect the actual path, method and any proxy prefix transformation. When it returns 200 with the wrong time, trace which release, configuration and data source provided that content. In each case use the earliest disagreement as the next check. Restarting services indiscriminately can hide the evidence without adding confidence that the problem is solved.
Record two final rows in your handoff. The first is a tested representative request during steady state, including the release name and expected useful result. The second is the concrete evidence that would trigger a reversal. For example, a repeated wrong schedule for the current approved link is a release failure even if readiness is 200. Give the owner a restoration route and a separate way to verify it through the same public hostname and path.
Read a service plan from the identity through the request
Suppose the dairy has accepted the Python code and wants to prepare an approved Linux VM. The site owner plans to have the application run as a dedicated user called dairy-app. The Python release is staged in a versioned directory, and the operator selects that release in the service configuration. Record these as choices before writing a unit. The operating-system user must exist and have read and execution permissions on the intended files. If the app needs to write any local data, place that data in an intended writable directory separate from the release.
The unit’s working directory names the release the service starts in. That choice affects relative file paths and Python module discovery. Its executable names Gunicorn in the release’s own environment. This avoids depending on a developer’s interactive activation command or a home directory the service cannot read. If the service expects an application factory, the final argument names that factory. Verify the module type and how the service receives its non-secret release ID before asking the owner for a start. A file named after your laptop’s Git checkout does not help if that folder is not present for the service’s actual user.
Put the private listener in the unit’s environment plan as a defined local address and port or a controlled socket, and give the frontend the matching target. If using a socket, check its permissions and parent directory traversal for the frontend account. A worker can make a new Unix socket when Gunicorn starts. An earlier reusable path does not prove that a current process is listening there. If using loopback TCP, choose a port that is available within this host and belongs to this particular service. Make process ownership explicit before investigating a connection from the frontend.
Check the service and the response in a predictable order. Ask the unit manager whether the exact named service is running. Inspect the scoped logs and look for the intended release and worker startup. Make an authorized request to the same private listener that the frontend uses. Then check the named frontend route and useful business output from the expected context. A system service that shows active can be running the wrong release or pointing at a mismatched setting. The private app and public request tests help establish the rest.
Plan failure behavior for configuration and data separately. A process cannot use a required setting that has not been delivered in its own environment. A controlled startup error can make an absent setting visible. An intermittent dependency may be better represented in application readiness or in a controlled operation error depending on how the service is designed. Explain which case should prevent startup and which case should keep the process alive while reporting it cannot do part of its work. Verify the diagnostics without exposing actual credentials.
Next make a three-line acceptance note. The expected process runs under dairy-app from the recorded release. The private test sees the correct pickup schedule marker at the intended listener. The public link gives the same correct behavior through the selected named frontend with certificate verification where applicable. Add a deliberately wrong path as a control. For a shared host, add a separately approved control route so the operator can notice if the wrong vhost changed.
Work through two interpretations of a proxy prefix
The dairy manager says the public route should be under /schedule/ since another service uses /pickup/ already. The backend application currently implements /pickup/east. The exact visitor link is now /schedule/pickup/east. Write the wanted public path and the wanted app path on opposite sides of a drawing. Decide which piece of configuration will translate between those paths. A redirect would expose a changed URL to the client, while a reverse proxy rewrite could preserve the public link.
In a simple Nginx prefix location such as location /schedule/, a proxy_pass containing an upstream address and a URI can replace the matching location portion in the normalized URI with the configured URI. An upstream ending in a slash uses that slash as its URI. For the simple example with a slash as the upstream URI, the backend would receive /pickup/east. With a name and port and no URI in the upstream directive, the ordinary case passes the request’s URI onward without that prefix replacement. Nginx documents additional details for rewrite, variable and regex situations, so do not extrapolate the example to every configuration.
Now suppose the same frontend uses a location intended for a static path. If the CSS file has been released correctly, a request for that file can succeed without reaching Gunicorn at all. That result tells you the frontend path and static release are working. It cannot distinguish the two proxy path interpretations. Choose a dynamic test and confirm that Flask’s actual observed path agrees with your selected route. Read the resulting status and a marker, not just whether the server produced HTML.
Pay attention to how the app generates links. If the browser should use the public prefix but Flask sends links rooted at another path, the first request can succeed while a subsequent navigation goes to the wrong service. Plan route generation, script root and any trusted prefix configuration in the intended architecture. Test the page link with the public host and from the path the student really uses. If the upstream wants to redirect from a route missing a trailing slash, inspect the actual Location including its hostname, scheme and prefix. A correct response body is one acceptance dimension within the longer journey.
Practice distinguishing the claims in this example. A 404 from the expected Flask release can mean the prefix was forwarded but not registered. A 404 from the default Nginx site can mean the frontend hostname did not select the intended location. An upstream connection error can mean Gunicorn never received any path. Use scoped logs and response markers to tell them apart. Test the approved final configuration with an unknown path to make sure it is deliberately handled.
Build a test matrix that discriminates failure modes
Take four lines from the lab and give each a specific claim. Correct east time proves a known operation through the controlled private socket. West returns the planned application-level error, so it proves the route rules distinguish known and unknown inputs. The worker replacement confirms that this model’s Gunicorn master noticed and replaced a child that exited. The socket closing confirms cleanup for the exercise. None of those individual claims requires a publicly available address. The corresponding application can still have a fault in its public path.
Write an analogous matrix for the separate web frontend. First select the named route and expected certificate. Test the exact dynamic operation over that route. Then ask a wrong path whose response you can predict, and one asset when a static mapping is present. For a staging versus production comparison, annotate the actual release markers. If a test uses a forced address or a special account, record that fact. Production clients may use another DNS resolver, address family or app permission. Run the final acceptance from the intended experience, with a harmless request that meets the goal.
For a failure case, decide what you would collect before touching a setting. A private socket unavailable to the frontend calls for process and permissions checks. A same-worker result after an intended replacement calls for the supervisor’s lifecycle event and identity evidence. A wrong schedule with the release marker present calls for the configuration or data source used by that route. A new 302 going to an HTTP address calls for trusted scheme propagation or canonical URL checks. Write these next to the symptom on the matrix.
Finish the review by translating one technical outcome to the dairy manager. To say the intended release is available, give the exact pickup address, the current schedule marker, and the time and relevant scope of the test. To say more evidence is needed, explain which path has been checked and which likely customer route remains. Do not promise future uptime merely because a controlled experiment handled one process change. This is how a small application test supports real deployment decisions.
Make a second row for the scope of your rollback test. If you restored only the app files and verified a public GET, say which runtime and data remained the same. If a candidate changed the route prefix, verify how the earlier frontend and application route will fit after restoring configuration. Involve the owner of customer data if a rollback changes what the app stored while the candidate was receiving requests. When the change is over, remove only temporary processes and directories that belonged to the rehearsal. Keep any replacement evidence that can be shared safely, including version, expected path, status and marker.
Explain what each upstream check can prove
What is the difference between Flask, Gunicorn and Nginx?
Flask implements application behavior and request routes. Gunicorn loads the WSGI application and manages workers accepting HTTP on its intended private endpoint. Nginx can accept the public request, handle TLS or static routes as configured and forward application requests. I test the route at each boundary before assuming the whole path works.
How would you diagnose a ModuleNotFoundError during service startup?
I would inspect which module the error names and compare the exact service command, working directory and Python environment. A missing local module can indicate a wrong import target or directory. A missing package may indicate that the selected environment lacks a dependency. I would verify the candidate under the same identity and interpreter the manager uses.
Why shouldn’t you reuse one fixed worker formula as a requirement?
Process count depends on workload, worker model, available cores and memory, and shared resources. I would choose a small starting configuration, measure useful throughput, latency and memory under representative conditions, and observe whether downstream dependencies can support additional concurrency.
How do you know if a restart supplied a working application?
A restarted process tells me about the supervisor. I would verify the intended release’s private app listener and representative operation, then the equivalent normal named frontend request. If the startup was intended to pick up new dependencies or data configuration, I would verify that specific evidence as well.
When can the app believe a forwarded scheme or client address?
Only when the deployment controls the incoming proxy path and the configured layers supply and interpret the intended values. The number of trusted proxy hops can differ by header. I would document which proxy sets each one, then verify the observed application behavior without giving arbitrary clients a direct backend route.
Predict the result before checking
Nginx returns a styled landing page, but the Gunicorn endpoint is unavailable. Could both be true?
Answer and reasoning
Yes. The frontend may serve static assets or one independent route while the proxy target for the application cannot respond. Test the exact dynamic path and active upstream.
Gunicorn imports
dispatch:create_app(). What does each part identify?Answer and reasoning
The left part is a Python module import and the right part is the function invocation yielding the WSGI application. The selected interpreter must be able to import that module and any required dependencies.
A worker gets a new PID under the same Gunicorn master. What evidence do you still need?
Answer and reasoning
A concrete route and release result. The worker process was replaced, but the maneuver alone does not prove the intended application loads or requests in flight were preserved.
The app expects
/pickup/east. Nginx forwards/dairy/pickup/east. Which layer’s configuration should you compare?Answer and reasoning
Compare the public path mapping with the Flask route. Choose whether the prefix belongs to the path the application sees and verify the exact observed URI after forwarding.
A process manager is enabled at boot. Does that prove a useful application response now?
Answer and reasoning
No. Enablement describes startup configuration. Verify the running process, private listener, current release and frontend route separately.
Cards for running a Python web service
Import target
Gunicorn imports a named module and loads an application or calls its factory. Test the correct interpreter and working directory.
Private upstream
Choose the intended socket or address. The public proxy and its private target need matching configuration and access.
Worker and service supervision
Gunicorn manages workers. A system manager can supervise the Gunicorn master according to the service’s configured policy.
Test the result
Check the exact named route and meaningful response marker in addition to process state and static files.
Version the release
Keep source, dependencies, configuration and data compatibility in the release plan. Test the scoped restoration path.
Official references
- Flask production deployment guidance
- Flask with Gunicorn
- Flask forwarded header settings
- Gunicorn master and worker design
- Gunicorn deployment, proxy and supervision
- Gunicorn runtime parameters
- Python WSGI interface
- Python virtual environments
- pip freeze inventory behavior
- Nginx proxy URI and headers
- systemd service configuration and restart policy
- curl Unix socket requests