hscloud-docs/03-build-web-app.md

2.6 KiB

Building your own Flask web service

In this chapter, we will build our own web service using the Flask framework, dockerize it and register it in the registry.

Requirements

Working nix. You can install nix with command:

sh <(curl -L https://nixos.org/nix/install) --daemon

and start it with:

nix-shell
bazel build //tools:install
bazel run //tools:install

You will require docker in this example. Install it from your standard shell.

curl -fsSL https://get.docker.com -o get-docker.sh
sudo sh get-docker.sh

You can actually create, build and register docker image in completely other environment, and just deploy it to kubernetes in hscloud environment.

Steps

We create a simple Flask application:

# app.py

from flask import Flask

app = Flask(__name__)

@app.route('/')

def hello_world():
    return 'Hello, World!'

if __name__ == '__main__':
    app.run()

We can check if the application works by running it:

pip3 install flask
python3 app.py

Now we create Dockerfile file for our application:

# Use an official Python runtime as a base image
FROM python:3.8-slim-buster

# Set the working directory in docker
WORKDIR /app

# Copy the current directory contents into the container at /app
COPY . /app

# Install any needed packages specified in requirements.txt
RUN pip install --upgrade pip && \
    pip install flask gunicorn

# Set environment variables
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0

# Expose port 5000 for the Flask app to listen on
EXPOSE 5000

# Define command to run the application using gunicorn
CMD ["gunicorn", "-w", "4", "-b", ":5000", "app:app"]

We can test if the application works in Docker:

docker build -t myflask .   # Build the image
docker run -d -p 5000:5000 myflask   # Run the container

We can check if the application works by opening the browser at http://localhost:5000.

Pushing the image to the registry

First, we need to authenticate to the registry:

https://registry.k0.hswaw.net

You should get command similar to:

docker login -u $hs_username -p *************** https://registry.k0.hswaw.net

Now we need to create local server for our docker image:

docker tag myflask registry.k0.hswaw.net/$hs_username/myflask:latest
docker push registry.k0.hswaw.net/$hs_username/myflask:latest

To check if the image is in the registry, you can use:

curl -X GET https://registry.k0.hswaw.net/v2/$hs_username/myflask/tags/list

To remove the image from the registry, you can use:

docker rmi registry.k0.hswaw.net/$hs_username/myflask:latest