Friday, February 7, 2020

REST on Python Flask for API's - 3

We put together a simple REST API application. Although it feeds of hard-coded data from inside, it is an independent service. Something like in a real-world scenario. We can certainly attach a data store to perform DB operations, but that's for another post. To run this service as an independent application, we need to wrap it in a Docker container. Let's do that now.


To run the application within Docker, use the following Dockerfile

Head over to the root directory of application and create a new ".Dockerfile". Add the following contents to it

As you can see from the above file, we use "ubuntu". If that image is too big, you can certainly try something like "ArchLinux"

FROM ubuntu
LABEL MAINTANER="Krishnan Sriram"
RUN apt-get update -y && \
    apt-get install -y python-pip python-dev
# We copy just the requirements.txt first to leverage Docker cache
COPY ./requirements.txt /app/requirements.txt
WORKDIR /app
RUN pip install -r requirements.txt
COPY . /app
ENTRYPOINT [ "python" ]

CMD [ "run.py" ]

To build this image, save it as ".Dockerfile" and run the following command

Change "flask-ubuntu" to name of your choice. I prefer to use a proper version, like below

docker build -t flask-ubuntu:1.0 .

After the build is successful, you can run it with the following command

docker run -d -p 500:5000 flask-ubuntu/1.0

If there are issues with your container instance, you can always go on to interactive mode to see what's happening with the instance

docker run -it -p 5000:5000 flask-ubuntu:1.0 /bin/bash

It's super handy to have a docker cheat-sheet around. If you can't find one, I'd say this is a good reference .



Our next objective will be to build and connect to a simple DB like Mongo or Postgres. We can try that on top of a simple, small but powerful ORM tool like SQLAlchemy.