Building Docker Images
A docker image is a file containing everything required to make an application run. This includes application executable, dependencies, libraries and runtime environment. A docker container is a running instance of an image.
To create a docker image, one needs to answer the question, how does this application normally run, without docker? This answer then guides the developer in creating a Dockerfile, which is a file using in specifying instructions for building a docker image.
Building a static HTML website docker image
How does a website run normally? To run a website, we need a web server, for example Nginx or Apache (feel free to choose either or even try both). We will then copy the static files to the root directory and the web server serves the content. With that information, we can create a file and name it Dockerfile. Our Dockerfile will look like this if we are to use the Apache web server:
FROM httpdCOPY html_directory /usr/local/apache2/htdocs/
Or this using Nginx web server:
FROM nginxCOPY html-directory /usr/share/nginx/html
The Dockerfile should be reference the html_directory folder relative to its location. It’s advisable to have the Dockerfile in the same folder as the html_directory. If it’s inside the directory, we will use COPY ./ in the Dockerfile.
To build an image, we need to run docker build command in the folder containing the Dockerfile. There’s more to this docker build command, but let’s keep it simple for now.
docker build -t my-static-web .
To confirm that our image was build successfully, we can list the available docker images using:
docker image ls
We expect to see such a thing
my-static-web latest 34607eb2e767 9 seconds ago 142MB
Building a Python docker image
How do we run Python normally?
- Install python in our environment
- Install any dependencies, e.g mysql-connector-python, flask, … etc
- To execute, we run `python file.py`.
If we have any external requirements, we will need to create a requirements.txt file in our python project folder. For example:
mysql-connector-python==8.0.23
scikit-learn==0.24.1
nltk==3.5
gensim==3.8.3
rake-nltk==1.0.4
pandas~=1.1.4
scipy~=1.6.0
tweepy~=3.9.0v
Our Dockerfile will contain:
# Choose your preferred python version
FROM python:3.8# Copy requirements to the docker image being created
COPY requirements.txt .# install dependencies
RUN pip install -r requirements.txt# copy the project files to the docker image
copy / .# specify the command to run when the container is started
CMD [ "python", "./main.py" ]
To build an image, we will run the build command in the folder containing the docker file.
docker build -t my-python-image .
To confirm that our image was build successfully, we can list the available docker images using:
docker image ls
That’s how to build a docker image. Remember to select your build image well to avoid incompatibility issues. In the python case, using python:3 instead of python:3.8 could throw syntax errors.