Skip to content
lorebow

Port binding

The app runs its own web server and serves HTTP on the port it is given, without depending on a server installed around it.

KFounder and editor 212 words 1 min read Find it on the map
On this page

Export services via port binding. A twelve-factor app is self-contained: it includes its own web server as a dependency, starts it, and listens on a port. Nothing has to be installed around it first.

That's different from the older model, where you dropped code into an Apache or Tomcat server that was already running on the machine. Here, the app is the server.

#Listen on the port you're given

The platform decides the port and passes it in, usually as PORT. The app reads it and falls back to a default for local work:

app.pypython
import os
from flask import Flask
 
app = Flask(__name__)
 
@app.get("/")
def index():
    return "Hello from the shop"
 
if __name__ == "__main__":
    app.run(host="0.0.0.0", port=int(os.environ.get("PORT", 5000)))
Two copies, two ports
$ PORT=8001 python app.py &
 * Running on http://0.0.0.0:8001
$ PORT=8002 python app.py &
 * Running on http://0.0.0.0:8002
$ curl localhost:8001
Hello from the shop
$ curl localhost:8002
Hello from the shop

0.0.0.0 means "accept connections on every network interface". Inside a container, listening on 127.0.0.1 would refuse traffic from outside it.

#Apps become backing services

Because each app is reachable at a URL and port, one app can be another app's backing service. Your shop can call a pricing service at PRICING_URL exactly the way it calls its database.

It isn't only HTTP, either. A Redis server and a game server bind a port too; they just speak a different protocol on it.

Referenced by