Loading [MathJax]/extensions/MathZoom.js

Monday, 21 May 2018

Starting with Docker

Until now, I've not done any work with containers so for a bit of fun I decided to setup my RESTful web server to run with Docker.

As a reminder, this is a simple python server built using web.py running on my Raspberry Pi Zero.

Step 1: Install Docker on Raspberry Pi
First up, install Docker. To do this, run these commands:

curl -sSL https://get.docker.com/sh

Set it up to start automatically on a reboot 

sudo systemctl enable docker:

Now add the pi user to the docker group, this means there'll be no need to use sudo in future:

sudo usermod -aG docker pi

Reboot, and then run:

docker run hello-world

pi@raspberrypi:~/Server $ docker run hello-world

Hello from Docker!
This message shows that your installation appears to be working correctly.


Success!

Step 2: Build Web server Image
The directory where the Dockerfile and build files is contained is called the context. The Dockerfile is a simple text file that contains the commands necessary to build the customised image.

All files used to build the image must be in the directory tree with this folder at its root:

pi@raspberrypi:~/Server $ ls
data  Dockerfile  RestServer.py


The image used to build for the Web server was a based on raspbian for Raspberry pi loaded from the docker hub. So starting from this point, the Dockerfile can be created:

FROM resin/rpi-raspbian:latest
ENTRYPOINT []

RUN apt-get -q update && \
    apt-get -qy install \
    python python-pip

RUN pip install web.py

WORKDIR /app

COPY RestServer.py /app

COPY data /home/pi/data/

CMD ["python", "RestServer.py"]


The script updates and installs python & python-pip before then using that to install web-py. It then setups the necessary directories and copies the python file along with the data folder for local storage.
Finally the CMD starts up the script using python.

This was then built with:

docker build -t rest-server .

Step 4: Run the Web server Container

Now to run the rest-server use this command

docker run -p 8080:8080 rest-server 

The -p argument exposes the 8080 port to external clients

This will start the container in the foreground and attach to stdout.

To run in "Detached" mode, use the -d flag. When starting this will return the long id of the container

Useful commands
Docker documents can be found here


To list the running containers:
docker ps

Open a bash shell into the image:
docker run -t -u rest-server /bin/bash 

List local docker images:
docker image ls

Delete a docker image
docker rmi <image id>

No comments:

Post a Comment