Create a Simple Docker Container with a Python Web Server
By Chris Bensen
If you’re curious about the goings-on of Oracle Developers in their natural habitat, come join us on our Slack channel for developers!
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.
- 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:
- Create server.py:
from http.server import BaseHTTPRequestHandler, HTTPServer
from socketserver import ThreadingMixIn
import threadinghostName = “0.0.0.0”
serverPort = 80class Handler(BaseHTTPRequestHandler):
# curl http://<ServerIP>/index.html
if self.path == “/”:
# Respond with the file contents.
content = open(‘index.html’, ‘rb’).read()
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:
Put Everything into a Docker Container
- Create Dockerfile:
ADD index.html index.html
ADD server.py server.py
ENTRYPOINT [“python3”, “server.py”]
- cd into the folder you created.
docker build -f Dockerfile . -t web-server-test
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.
Next, try creating an Oracle Cloud account Free Tier, and deploy your container there. Who knows, maybe I’ll create a How To for that in the future!