Package a Python HTTP service
A small example
FROM python:3.13-slimWORKDIR /appCOPY app.py .USER 10001:10001EXPOSE 8080CMD ["python", "-u", "app.py"]The base supplies Python; the file supplies a single GET endpoint. The -u option makes Python standard output and error unbuffered, useful for observing logs. The application uses HTTPServer only for learning, not production. Its response body and status are independent of the Docker build output. A real application often depends on third-party packages: review a fully resolved, version-pinned dependency manifest (and hashes where appropriate), install dependencies in a controlled build step before copying frequently changing source, and test the target platform. Do not install arbitrary dependencies during container startup. This example avoids packages entirely, so no dependency download is necessary. Python source and the Dockerfile are separate files.
Try it in a local lab
Manual lab only; basic language familiarity is helpful, but every source file is supplied. Use a fresh authorized disposable Linux VM with blocked external egress, a local Engine and local Buildx docker driver. Check docker context show, docker version, docker buildx version and docker buildx ls. Verify the reviewed preloaded native base image named in the recipe, its digest, tool versions, inherited entrypoint, file permissions and required commands. Tags are mutable. Confirm all bm-v11 names and tags are unused. Stop if any input must be fetched or a builder is remote. --network none at build time constrains RUN, not all builder traffic. Runtime --network none leaves container loopback only. No public ports, credentials, host mounts or registry access. Execute separately, stop on unexpected failure, and dispose of the VM even if cleanup fails. All Docker results are predictions. Before contacting any Engine or builder, verify the effective endpoint of this exact command, including DOCKER_CONTEXT, DOCKER_HOST and builder overrides. Use only a reviewed fixture directory containing the listed inputs. Check the build exit status and record the loaded image ID before running; a failed build does not clear an older tag.
Open lab-fixtures/docker-application-packaging/02-python-service/ in the extracted archive. The Dockerfile and these files are supplied. Work on a disposable copy, not the original archive.
from http.server import BaseHTTPRequestHandler, HTTPServer
class Handler(BaseHTTPRequestHandler): def do_GET(self): if self.path != "/health": self.send_error(404) return body = b"ready\n" self.send_response(200) self.send_header("Content-Type", "text/plain") self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body)
if __name__ == "__main__": HTTPServer(("127.0.0.1", 8080), Handler).serve_forever()docker build --load --network none --progress=plain -t bm-v11-python-service:lab .docker run -d --name bm-v11-python-service --pull=never --network none bm-v11-python-service:labCheck container state and logs first. For HTTP, try the bounded probe once, and if startup is still in progress repeat once after a short interval. If it still fails, stop and diagnose. For the worker, confirm its ready message before stopping.
docker exec bm-v11-python-service python -c "from urllib.request import urlopen; print(urlopen('http://127.0.0.1:8080/health', timeout=3).read().decode().strip())"# Run only after the positive probe succeeds.docker exec -i bm-v11-python-service python - <<'PYTHON'from urllib.request import urlopenfrom urllib.error import HTTPErrortry: urlopen('http://127.0.0.1:8080/missing', timeout=3)except HTTPError as error: assert error.code == 404 print(error.code)else: raise AssertionError('expected HTTP 404')PYTHONExpect ready after startup. An unknown path returns HTTP 404 rather than the health response. The probe must run inside the container because the service listens only on its loopback interface. Detached startup is not readiness. Check the named container is running and inspect bounded logs if the first request fails. Retry the documented probe only within a 15-second startup budget; stop and diagnose if it still fails. Record response and command exit status. The second command succeeds only for HTTP 404; a connection error or unexpected status fails the test.
Confirm names and tag belong to this lab. For a service, stop it if still running and remove only the named container. Then remove only this image tag without forcing. If a command fails, inspect state before continuing; do not remove unrelated objects. Dispose of the VM rather than clearing a shared cache.
docker stop -t 5 bm-v11-python-servicedocker rm bm-v11-python-servicedocker image rm bm-v11-python-service:labCommon mistake
A built image is not proof of a working service. Check the endpoint, process state and logs separately.
Manual practice
Add a second endpoint /version returning v1 in your lab copy. Describe expected status and body for both paths and an unknown path, then rebuild before testing.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Package a Python HTTP service — Knowledge check
Apply the application packaging concept to a new scenario.
What provides the interpreter?
Why lock external dependencies in a real project?
What verifies the endpoint?