Building a small CRUD app using docker
Introduction
Let’s try to build a small application using docker. This will help us understand some basic dockers commands.
Building the Application
We’re going to build a small Python Flask App, where we’ll hit an endpoint to increase the value of a variable vote.
First we’ll install flask
$ pip install flask
Now let’s create a python file called app.py
Now we’ll import the Flask
library, and create the app.
from flask import Flask, jsonify
app = Flask(__name__)
Next Let’s create declare a global variable called vote
. This is the value we’re going to increment using an endpoint.
And we’ll also declare a method to increment this value and map this to the endpoint /vote
vote_count = 0
@app.route('/vote')
def vote():
global vote_count
vote_count = vote_count +1
return jsonify(vote_count)
Finally we’ll write the main
method to run this application on port 5000
if __name__ == '__main__':
app.run(port=5000, debug=True, host='0.0.0.0')
Okay so now we have built the python application. Let’s try running this app now.
$ python app.py
Now that the application has started on port 5000
, let’s open another tab and hit the localhost:5000/vote
endpoint
using curl
$ curl localhost:5000/vote
We’ll see that the count of vote is 1
Now let’s try hitting the same endpoint again a couple of times.
We see that the value of the vote variable has increases everytime we hit the endpoint.
Okay so now that we have built the base python application. Let’s try to create docker images of the application and run them using docker.
Creating Docker image
Let’s just dive into creating docker images.
To create a docker image for out vote application, we’ll first need to create a Dockerfile
.
In the same root directory, where we have the app.py
, let’s create a file called Dockerfile
FROM python:3.8-alpine3.12
WORKDIR /usr/src/
COPY . /usr/src/
RUN pip install -r requirements.txt
CMD ["flask", "run", "--host", "0.0.0.0"]
Let’s go through what’s happening in the contents of this file.
The first line FROM python:3.8-alpine3.12
tells docker to use the Python:3.8-alpine
as the base image for our vote application. This will give us the core python capabilities
The second line means we’re going to use /usr/src/
as our work directory.
In the third line we’re copying the contents from our root directory to the work directory that we had set earlier. This will copy all our files to /usr/src/
Next we’ll run the pip install command to install all out dependencies. In our case that is Flask
.
Finally we’ll start the application, using flask run
Okay so now we have the docker file ready. Next we’re going to build the docker image for our vote-application.
$ docker build -t vote-app:v0.1 .
We’re using the docker build
command to build the application. vote-app
is the name of our image and v0.1
is the tag,
running this command will build the docker image as seen below
Now let’s run
$ docker images
and we’ll see that we have a image called vote-app
created