Python Console App with Docker

Create the Python script

Let’s create a simple python script. We’ll call the file inside a src folder of the project.

#src/script.pyprint('hello world!')

Create the Dockerfile

#DockerfileFROM python:3.6RUN mkdir /application
WORKDIR "/application"
# Upgrade pip
RUN pip install --upgrade pip
# Update
RUN apt-get update \
&& apt-get clean; rm -rf /var/lib/apt/lists/* /tmp/* /var/tmp/* /usr/share/doc/*
ADD requirements.txt /application/
ADD src/ /application/
RUN pip install -r /application/requirements.txtCMD [ "python", "" ]

How to run

In your console, build the docker image

docker build -t python-script .
docker run python-blog-scraper


You might ask yourself, why not just run the script, i.e python from the console? My answer to that is, because of the requirements. As I mentioned earlier, systems change and it’s not realistic to think that you’ll always have the python version you need with the pip requirements installed.

import requests
from bs4 import BeautifulSoup
class BlogPost:
title = None
first_sentence = None
def __init__(self, title, first_sentence):
self.title = title
self.first_sentence = first_sentence
def __str__(self):
return str(self.title) + '\n' + str(self.first_sentence)
def scrape(url):
r = requests.get(url)
if r.status_code == 200:
soup = BeautifulSoup(r.content, features="html.parser")
# print(soup.prettify())
for article in soup.find_all('article', attrs={'class': 'post'}):
title = article.find('h2', attrs={'class': 'entry-title'}).string
first_sentence = article.find('div', attrs={'class': 'entry-content'}).find('p').string
blog_post = BlogPost(
print('Whoops! Something went wrong!')
ADD requirements.txt /application/
ADD src/ /application/
RUN pip install -r /application/requirements.txtCMD [ "python", "" ]
docker build -t python-script .
docker run python-blog-scraper

Conclusion and Resources

As you can see, we’ve added requirements and packaged everything in a Docker image, so we can easily deploy this simple app to any machine that has docker installed and run it with no requirement missing or version issues.



Coder, Entrepreneur, Co-founder at SlowCode

Love podcasts or audiobooks? Learn on the go with our new app.

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store