This set up
describes about a multi docker container setup with python and mysql.
We will create two
container, one for Python App and another for Mysql and will the communication between each.
==> Create a Dockerfile for mysql-server.
#Pull Docker image.
FROM mysql:5.6
ADD nsebackup.sql
/nsebackup.sql
==> Build the image
#docker build -t
mysql-local-image .
==> Create the
conatiner with local mouneted volume. Create the local directory on host.
#mkdir /datadir
# docker run -d
--name mysql-local-server -p 3306:3306 -v
/datadir:/var/lib/mysql -e
MYSQL_ROOT_PASSWORD=xxx mysql-local-image
==> you
should able to see the container "mysql-local-server" running on the hsot
using docker ps commnd.
#### Create the
python app container####
==> Create a Dockerfile for python app.
# 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 -r
requirements.txt
# Make port 80
available to the world outside this container
EXPOSE 8000:8000
CMD
["python", "app.py"]
==> Create app.py
from flask import
Flask
import
mysql.connector as mariadb
def fnconnDB():
myhost
= os.environ.get('MYSQL_LOCAL_IMAGE_PORT_3306_TCP_ADDR') #this will get the db server's IP which need to link during the docker
run command. see the below docker run commnd
mariadb_connection
= mariadb.connect(host=myhost,user='xxx', password='xxx',database='xxx')
return
mariadb_connection
#......your codes….
#
if
__name__=="__main__":
app.run(host='0.0.0.0',port=int('8000'),debug=True,threaded=True)
==> Build the image
#docker build -t
mysql-python-image .
==> run the conatiner with --link option, which will set
mysql environment on python app container.
Syntax => docker
run -d -p 8000:8000 --link <mysql container name>:<mysqk container
image name> --name mysql-python-app mysql-python-image
#docker run -d -p
8000:8000 --link mysql-local-server:mysql-local-image --name mysql-python-app
mysql-python-image
No comments:
Post a Comment