PROJECTS NOTES HOME

Docker test container

An example of a Docker container that runs a flask web app inside of it.

1 Create Needed files

Create a directory in which you will put 3 files:

  • Dockerfile
  • server.py
  • helloworld.html

1.1 Dockerfile content

FROM python:3.9-slim
WORKDIR /app
COPY server.py .
COPY helloworld.html .
EXPOSE 8082
CMD ["python3", "server.py"]

1.2 server.py content

import http.server
import socketserver
# Define the port number
PORT = 8082
# Define the request handler class
class MyRequestHandler(http.server.SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        http.server.SimpleHTTPRequestHandler.end_headers(self)

    def do_GET(self):
        # If the requested path is "/", serve helloworld.html
        if self.path == '/':
            self.path = '/helloworld.html'
        elif self.path == '/favicon.ico':
            self.send_response(204)  # No content
            return
        return http.server.SimpleHTTPRequestHandler.do_GET(self)
# Set up the server
with socketserver.TCPServer(("", PORT), MyRequestHandler) as httpd:
    print(f"Serving at port {PORT}")
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        pass

1.3 helloworld.html content

<!DOCTYPE html>
<html>
  <head>
    <title>Hello World</title>
  </head>
  <body>
    <h1>Hello, World!</h1>
  </body>
</html>

2 Build the image

While in the same directory as the previous 3 files, run:

docker build . -t test

Check docker desktop(if on windows) or docker images to see the newly created image called test

3 Run the image

docker run -it - p 5009:8082 test

visit http://localhost:5009/

PS C:\Users\hello> docker run -it -p 5009:8082 test
Serving at port 8082
10.10.0.1 - - [03/Jan/2024 13:27:26] "GET / HTTP/1.1" 304 -
10.10.0.1 - - [03/Jan/2024 13:27:26] "GET /favicon.ico HTTP/1.1" 204 -
10.10.0.1 - - [03/Jan/2024 13:27:26] "GET /favicon.ico HTTP/1.1" 204 -
10.10.0.1 - - [03/Jan/2024 13:27:27] "GET / HTTP/1.1" 304 -

Just C-c C-c to stop the image from running.