Create a Simple Docker Container with a Python Web Server
By Chris Bensen

If you prefer you can read this blog post on GitHub here.
This article may seem obvious to some, but others need to know how to get started. Having a server running in a container is the beginning of so many great things.
Prerequisites
- Install Docker.
- Read Create a Simple Python Web Server because we will use this Web Server but put it into a Docker container.
Build a Web Server
- Create a folder and put all the files we are going to create into that folder.
- Create index.html:
<!DOCTYPE html>
<html>
<body>
Hello World
</body>
</html> - Create server.py:
#!/usr/bin/python3
from http.server import BaseHTTPRequestHandler, HTTPServer
import time
import json
from socketserver import ThreadingMixIn
import threadinghostName = “0.0.0.0”
serverPort = 80class Handler(BaseHTTPRequestHandler):
def do_GET(self):
# curl http://<ServerIP>/index.html
if self.path == “/”:
# Respond with the file contents.
self.send_response(200)
self.send_header(“Content-type”, “text/html”)
self.end_headers()
content = open(‘index.html’, ‘rb’).read()
self.wfile.write(content)else:
self.send_response(404)returnclass ThreadedHTTPServer(ThreadingMixIn, HTTPServer):
“””Handle requests in a separate thread.”””if __name__ == “__main__”:
webServer = ThreadedHTTPServer((hostName, serverPort), Handler)
print(“Server started http://%s:%s" % (hostName, serverPort))try:
webServer.serve_forever()
except KeyboardInterrupt:
passwebServer.server_close()
print(“Server stopped.”)
```
Put Everything into a Docker Container
- Create Dockerfile:
FROM python:3
ADD index.html index.html
ADD server.py server.py
EXPOSE 8000
ENTRYPOINT [“python3”, “server.py”] - cd into the folder you created.
- Run
docker build -f Dockerfile . -t web-server-test
- Run
docker run -rm -p 8000:80 — name web-server-test web-server-test
There you have it! Enjoy your web server in a Docker container. The nice thing about doing this is as a developer you can run and debug things inside a container just as if they are on your local computer but the only thing that is installed on your local system is Docker.