Set up your first microservice using Flask and Docker: Part 2

H A M II™
HacksNextDoor
Published in
2 min readJul 29, 2018
Port of Oakland

Since you’ve built your first service now its time to package it up and 🚢 it for all your friends to see! But how do you exactly do it? No worries I’ll be showing you the industry standard for packaging up a service and making it seamless to deploy to any cloud service (Now, Heroku, AWS, Google Cloud, etc) Learning how to use docker not only works for python services, but any a web app you may want deploy.

What is Docker?

Docker is the company driving the container movement and the only container platform provider to address every application across the hybrid cloud.

A container image is a lightweight, stand-alone, executable package of a piece of software that includes everything needed to run it: code, runtime, system tools, system libraries, settings.

How to integrate Docker

Go into your project directory in this case if you are cd my-flask-microservice

Create the following Dockerfile:

# Use an official Python runtime as a parent image
FROM python:2.7-slim

# Set the working directory to /app
WORKDIR /app

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

# Install any needed packages specified in requirements.txt
RUN pip install --trusted-host pypi.python.org -r requirements.txt

# Make port 80 available to the world outside this container
EXPOSE 80

# Define environment variable
ENV NAME World

# Run app.py when the container launches
CMD ["python", "app.py"]
  • Now run the build command. This creates a Docker image, which we’re going to tag using -t so it has a friendly name.
docker build -t friendlyhello .
  • Run the app, mapping your machine’s port 4000 to the container’s published port 80 using -p:
docker run -p 4000:80 friendlyhello

Now let’s run the app in the background, in detached mode by adding option-d:

docker run -d -p 4000:80 friendlyhello

You get the long container ID for your app and then are kicked back to your terminal. Your container is running in the background. You can also see the abbreviated container ID with docker container ls (and both work interchangeably when running commands):

$ docker container ls
CONTAINER ID IMAGE COMMAND CREATED
1fa4ab2cf395 friendlyhello "python app.py" 28 seconds ago

You’ll see that CONTAINER ID matches what’s on http://localhost:4000.

Congrats! You’ve setup you first docker container. 🎉

Now use docker container stop to end the process, using the CONTAINER ID, like so:

docker container stop 1fa4ab2cf395

Reference: https://docs.docker.com/get-started/part2/#tag-the-image

Written next door 🖥

--

--