Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Easy construction]

Introduction

My name is Ryosuke Kamei and I am an IT consultant based on the idea of "gentle IT"! Currently, in my work, I am doing upstream processes focusing on requirements analysis and requirements definition, but since I am also writing programs other than my main business, I will write technical articles! As part of our friendly IT activities, we will introduce the goods and services programs created with "Raspberry Pi 3" (commonly known as Raspberry Pi), which has the philosophy of "providing inexpensive PCs that can be programmed for education"!

Purpose

Build a Python-MySQL environment with Docker on Raspberry Pi. Actually, I aimed to start it with docker-compose, but only application server construction and SQL execution did not work. The infrastructure level is still low. Excuse me. However, I think it will be of some help! The data registered in the database assumes the temperature acquisition detected by Raspberry Pi.

Premise

Assuming that Docker and Git are installed on the Raspberry Pi, you can build a sample by executing the following commands in order in any folder. See the article below for installing Docker and Git. Install Docker and Git on RaspberryPi3

Move for the time being

I want to see what is moving! If you are impatient like me, please execute the commands in the following order in any folder of Raspberry Pi.

I verified it in the / home / pi / Workspace folder.

Movement

Clone with git and download the file


$ git clone [email protected]:RyosukeKamei/rpi-python-bottle.git

Move to cloned folder


$ cd rpi-python-bottle

docker-Build and start data container and database container with compose


$ docker-compose up -d

Check the image


$ docker images

Check the container


$ docker ps -a

Login to database container


$ docker exec -it rpi-python-bottle-db bash

Enter sample table and data


# mysql -u bottle -pbottle measurement < /docker-entrypoint-initdb.d/create_table.sql

Log out database container


# (Contrl + p, Control + q)

Build application container


$ docker build -t hypriot/rpi-python .

Start the application container and log in


$ docker run --name rpi-python-bottle-app -it hypriot/rpi-python bash

Start the server


# /usr/local/bin/python3 /home/bottle/server.py

When you open it in a browser, it will be displayed as follows. ブラウザで確認

Let's explain!

table of contents

  1. Preparation
  2. Git clone a series of files
  3. Start with docker-compose
  4. Log in to the database container (MySQL) and create data
  5. Build the application container
  6. Application server settings

1. Preparation

If you do not have Docker or development environment, please refer to the following. If you have Docker installed, you can skip it!

1-1. Install Docker

See Install Docker on RaspberryPi3!

1-2. Convenient functions (SSH / VNC / AFP)

It is convenient to implement the following chapter of Raspberry Pi 3 installation → wireless LAN → Japanese input / output → operation from Mac (SSH / VNC server / AFP).

  1. Access by SSH
  2. VNC settings (manipulate Raspberry Pi from Mac with GUI)
  3. AFP settings (access Raspberry Pi file system on Mac)

2. Git clone a series of files

git clone


pi@raspberrypi $ git clone [email protected]:RyosukeKamei/rpi-python-bottle.git

Move


pi@raspberrypi $ cd rpi-python-bottle

3. Start database and data container with docker-compose

3-1. Start with docker-compose

docker-Start with compose


pi@raspberrypi $ docker-compose up -d

3-2. docker-compose.yml For reference, docker-compose.yml is described.

docker-compose.yml


data:
  container_name: rpi-python-bottle-data
  image: hypriot/armhf-busybox
  stdin_open: true
  tty: false
  volumes:
    - ./docker/mysql:/etc/mysql/conf.d:ro
    - ./app:/home/bottle
  command: /bin/sh

mysql:
  container_name: rpi-python-bottle-db
  image: hypriot/rpi-mysql
  volumes:
   - ./initdb.d:/docker-entrypoint-initdb.d
  environment:
    MYSQL_ROOT_PASSWORD: password
    MYSQL_USER: bottle
    MYSQL_PASSWORD: bottle
    MYSQL_DATABASE: measurement
  ports:
    - "3306:3306"
  volumes_from:
    - data

4. Log in to the database container (MySQL) and create data

volumes in docker-compose.yml: ./initdb.d:/docker-entrypoint-initdb.d If you set, the file directly under the "initdb.d" folder placed locally will be placed under the "/docker-entrypoint-initdb.d" folder on the container, and the file described by SQL will be executed automatically. It should be, but it doesn't seem to work ... There is no choice but to create the data manually.

4-1. Procedure

Log in to the database server


pi@raspberrypi $ docker exec -it rpi-python-bottle-db bash

Execute the file in which SQL is written


root@{Container ID}:/# mysql -u bottle -pbottle measurement < /docker-entrypoint-initdb.d/create_table.sql

Caution Do not put a space after -p. MySQL user name, password and database name are set in docker-compose.yml. This is a temporary one, so please change it for security reasons.

Exit the database container


root@{Container ID}:/# (Contrl + p, Control + q)

4-2. SQL SQL is posted for reference.

mysql:/docker-entrypoint-initdb.d/create_table.sql


mysql>
CREATE TABLE `temperatures` (
  `id`           int(11) NOT NULL AUTO_INCREMENT,
  `server_id`    int(11) NOT NULL,
  `temperature`  int(11) NOT NULL,
  `careted_at`   datetime NOT NULL,
  `careted_user` int(11) NOT NULL,
  `updated_at`   datetime NOT NULL,
  `updated_user` int(11) NOT NULL,
  KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

Insert data


mysql>
INSERT INTO `temperatures` 
  (`id`, `server_id`, `temperature`, `careted_at`, `careted_user`, `updated_at`, `updated_user`) 
  VALUES 
  (1, 1, 29, NOW(), 1, NOW(), 1);

5. Build the application container

Details will be explained in another article.

5-1. Build application container from Dockerfile

Build application container


pi@raspberrypi $ docker build -t hypriot/rpi-python .

5-2. Installed

I installed the following with apt-get.

Python library to install with pip3

After that, I'm creating a user and setting up vim for Python.

6. Application server settings

Originally, I would like the application server to start as well, but this was not started.

6-1. Check server.py

server.py will be copied locally to "/ home / bottle".

Start the application server and log in


pi@raspberrypi: $ docker run --name rpi-python-bottle-app -it hypriot/rpi-python bash

Check where you logged in


# pwd
/home/bottle

6-2. Launch the application

Application launch


# /usr/local/bin/python3 /home/bottle/server.py

6-3. Check with a browser

When you open it in a browser, it will be displayed as follows. ブラウザで確認

6-4. Plugram server.py

The program is described for reference.

server.Check py (fix this file if there is a problem)


# vim server.py

server.py


#bottle library
from bottle import route, run, request

#MySQL driver is mysql.connector
import mysql.connector

#Supplement
#Actually, if you put a template, the HTML will be beautiful.
#That area will come later ...

#The IP address of host is$ docker inspect {Database container name}Find out in
#MySQL users, passwords and databases are docker-compose.What was set in yml
# user     : MYSQL_USER
# password : MYSQL_PASSWORD
# database : MYSQL_DATABASE
connector = mysql.connector.connect (
            user     = 'bottle',
            password = 'bottle',
            host     = '172.17.0.3',
            database = 'measurement'
)


			
@route('/list')
def list():
    #Show temperature
    cursor = connector.cursor()
    cursor.execute("select `id`, `temperature`, `careted_at` from temperatures")

    disp  = "<table>"
    #header
    disp += "<tr><th>ID</th><th>temperature</th><th>Registration date</th></tr>"
    
    #List part
    for row in cursor.fetchall():
        disp += "<tr><td>" + str(row[0]) + "</td><td>" + str(row[1]) + "</td><td>" + str(row[2]) + "</td></tr>"
    
    disp += "</table>"
    
    cursor.close

    return "Get from DB"+disp

@route('/input_temperature')
def input_temperature():
    #Enter temperature
    cursor = connector.cursor()
    cursor.execute("INSERT INTO `temperatures` (`server_id`, `temperature`, `careted_at`, `careted_user`, `updated_at`, `updated_user`) VALUES (" + request.query.server_id + ", " + request.query.temperature + ", NOW(), " + request.query.user_id + ", NOW(), " + request.query.user_id + ")")

    #commit
    connector.commit();

    cursor.close

    return "OK"
    

#Close connector
connector.close

#Server startup
run(host='0.0.0.0', port=8080, debug=True, reloader=True)

6-5. If not displayed

The IP address of the application server or database server may differ depending on the order or environment. Exit the container, return to Raspberry Pi and check the IP address.

IP address confirmation


$ docker inspect {Container name or container ID}

There should be an IP address, so please access it from your browser as it is! If you get a database error, change the IP address of the server.py database!

If there is no data, you should see a MySQL error in the container. 4. Log in to the database container (MySQL) and create data Please try again!

Finally

docker-compose It wasn't a single shot, but ... It seems that you can build a Docker + Python + bottle + MySQL environment on Raspberry Pi!

site map

Raspberry Pi 3 setup

Install Raspberry Pi 3 → Wireless LAN → Japanese input / output → Operate from Mac

Build a Python + MySQL environment with Docker on Raspberry Pi 3!

Install Docker on RaspberryPi3 Build a Python + bottle + MySQL environment with Docker on RaspberryPi3![Easy construction] Build a Python + bottle + MySQL environment with Docker on RaspberryPi3![Trial and error]

Make an air conditioner integrated PC "airpi" with Raspberry Pi 3!

Make an air conditioner integrated PC "airpi" with Raspberry Pi 3!

Finally ... Make a radio control using python on Raspberry Pi 3!

Motor moves while pressing the button The motor moves while the magnet is brought closer The motor moves when the magnet is brought closer and stops automatically

Let's play with Raspberry Pi 3 and python Record of Raspberry Pi struggle

Programming with Node-RED programming with Raspberry Pi 3 and programming normally Light the LED with python on Raspberry Pi 3 (Hello World) Detect switch status on Raspberry Pi 3 Run a servo motor using python on Raspberry Pi 3 Control the motor with a motor driver using python on Raspberry Pi 3! Detect slide switch using python on Raspberry Pi 3! Detect magnet switch using python on Raspberry Pi 3! Detect temperature using python on Raspberry Pi 3! Sound the buzzer using python on Raspberry Pi 3! Detect analog signals with A / D converter using python on Raspberry Pi 3! Detect "brightness" using python on Raspberry Pi 3! Detect "temperature (using A / D converter)" using python on Raspberry Pi 3! Output to "7-segment LED" using python on Raspberry Pi 3! Use python on Raspberry Pi 3 to light the LED with switch control! Use python on Raspberry Pi 3 and turn on the LED when it gets dark!

Rules focused on test-driven development

Coding rules "Let's write gentle code" (FuelPHP) Naming convention "Friendly to yourself, team-friendly, and unseen members after 3 months"

Web application development with Docker + Python

Install Python3, related libraries pip, virtualenv and frameworks Django, bottle, Flask on CentOS on Docker! With a Dockerfile that summarizes these!

Easy to develop environment construction (Docker + PHP)

PHP environment + Eclipse is linked to Apache using Docker Building FuelPHP development environment using Docker Create CRUD skeleton using initial settings of FuelPHP development environment using Docker and scaffold FuelPHP database migration

Recommended Posts

Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Easy construction]
Build a Python + bottle + MySQL environment with Docker on RaspberryPi3! [Trial and error]
Build Mysql + Python environment with docker
Build a python environment with ansible on centos6
[Python] Build a Django development environment with Docker
How to build a Django (python) environment on docker
Build a python3 environment on CentOS7
Build Jupyter Lab (Python) environment with Docker
Build a python environment on MacOS (Catallina)
Build Python environment with Anaconda on Mac
[Linux] Build a jenkins environment with Docker
Build a python virtual environment with pyenv
Build a Python + OpenCV environment on Cloud9
Build a modern Python environment with Neovim
Build NGINX + NGINX Unit + MySQL environment with Docker
[Linux] Build a Docker environment with Amazon Linux 2
Build a 64-bit Python 2.7 environment with TDM-GCC and MinGW-w64 on Windows 7
Build a Python environment on your Mac with Anaconda and PyCharm
Build a WardPress environment on AWS with pulumi
Simply build a Python 3 execution environment on Windows
Build a Django environment on Raspberry Pi (MySQL)
Build a Python environment on Mac (Mountain Lion)
Create a python3 build environment with Sublime Text3
Build a Python development environment on your Mac
Build a Python environment with OSX El capitan
Quickly build a Python Django environment with IntelliJ
Build PyPy and Python execution environment with Docker
Build a Python machine learning environment with a container
Build a Python development environment on Raspberry Pi
Build a python execution environment with VS Code
Easy Python data analysis environment construction with Windows10 Pro x VS Code x Docker
Build a local development environment with WSL + Docker Desktop for Windows + docker-lambda + Python
Virtual environment construction with Docker + Flask (Python) + Jupyter notebook
Build a GVim-based Python development environment on Windows 10 (3) GVim8.0 & Python3.6
# 2 Build a Python environment on AWS EC2 instance (ubuntu18.04)
Build a python virtual environment with virtualenv and virtualenvwrapper
[Python] OpenCV environment construction with Docker (cv2.imshow () also works)
Build a machine learning Python environment on Mac OS
From Kafka to KSQL --Easy environment construction with docker
Build a python environment for each directory with pyenv-virtualenv
I made a Python3 environment on Ubuntu with direnv.
Build a GVim-based Python development environment on Windows 10 (1) Installation
Build a Python development environment on Mac OS X
Build a Python virtual environment using venv (Django + MySQL ①)
Build a Python environment on your Mac using pyenv
Build a machine learning application development environment with Python
Build a python virtual environment with virtualenv and virtualenvwrapper
Easy build of C ++ code with CMake on Docker
Build a Python development environment using pyenv on MacOS
Build a development environment with Poetry Django Docker Pycharm
How to build a Python environment on amazon linux 2
Build python3 environment with ubuntu 16.04
Build Python environment on Windows
Prepare python3 environment with Docker
Build python environment with direnv
Build python environment on windows
Build a Python environment offline
Build a basic Data Science environment (Jupyter, Python, R, Julia, standard library) with Docker.
OpenJTalk on Windows10 (Speak Japanese with Python from environment construction)
Build a python machine learning study environment on macOS sierra
Build a Django development environment with Docker! (Docker-compose / Django / postgreSQL / nginx)