Deploy Nginx+Flask+Mongo application using Docker

Deploy Nginx+Flask+Mongo application using Docker

Nginx is used as the server, Mongo is used as the database support, and Flask is the Python language web framework. Using the container characteristics of Docker, it can be easily deployed on a Linux server.

Project Preparation

The main directory of the project is as follows

__project-name
  |__ docker-file
    |__ ningx
      |__ Dockerfile
      |__conf
        |__ nginx.conf
    |__flask
      |__ Dockerfile
      |__ requirements.txt
    |__ mongo
      |__ Dockerfile
      |__ setup.sh
    |__docker-compose.yml
  |__src
    |__ app
      |__ ...
    |__run.py

Brief Description

The docker-file directory is the configuration file for docker deployment

The src directory is the python code of the flask application

Docker detailed configuration

docker-compose configuration

version: '2.2'
services:
 mongo:
  build: ./mongo
  volumes:
   - "./mongo/db:/data/db"
  restart: always
  ports:
   - "27017:27017"
  environment:
   MONGO_INITDB_ROOT_USERNAME: root
   MONGO_INITDB_ROOT_PASSWORD: 123456
 flask:
  build: ./flask
  links:
   - mongo
  ports:
   - "5000:5000"
  expose:
   - "5000"
  volumes:
   - ../src:/home/web
 nginx:
   build: ./nginx
   links:
    - flask
   volumes:
    - "./nginx/log:/var/log/nginx"
    - "../:/usr/share/nginx/html"
   ports:
    - "80:80"
    - "8080:8080"
    - "443:443"
   restart: always

MongoDB Configuration

The contents of /mongo/Dockerfile are as follows

FROM mongo:3.6
# Set time zone ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# Set the working directory ENV WORKDIR /usr/local/work
ENV AUTO_RUN_DIR /docker-entrypoint-initdb.d
ENV INSTALL_MONGO_SHELL setup.sh
RUN mkdir -p $WORKDIR
# Copy the database initialization command COPY ./$INSTALL_MONGO_SHELL $AUTO_RUN_DIR/
RUN chmod +x $AUTO_RUN_DIR/$INSTALL_MONGO_SHELL

The content of /mongo/setup.sh is as follows

The purpose of this file is to create a user test with a password of test after starting MongoDB, and grant it read and write operations on the database test

#!/bin/bash
mongo <<EOF
use admin;
db.auth('root', '123456');
use dmx_aluminum;
db.createUser({user:'test',pwd:'test',roles:[{role:'readWrite',db:'test'}]});
db.createCollection("user");
EOF

Flask application configuration

The contents of /flask/Dockerfile are as follows

FROM python:3.6
# Set time zone ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone

# Set up the workspace RUN mkdir -p /home/web
WORKDIR /home/web
# Add dependencies ADD requirements.txt /home/web/requirements.txt
RUN pip3 install -i https://pypi.douban.com/simple/ -r requirements.txt

# Use gunicorn to start the application CMD gunicorn -w 4 -b 0.0.0.0:5000 run:app

/src/app/run.py code

The app.run() for debugging is commented here, and it is started with gunicorn when publishing.

from app import create_app
app = create_app('default')
app.debug=False
# if __name__ == '__main__':
# app.run()

Nginx Configuration

The content of /nginx/Dockerfile is as follows

FROM nginx:1.14
# Set time zone ENV TZ=Asia/Shanghai
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
# Copy configuration COPY conf/nginx.conf /etc/nginx/nginx.conf

The content of /nignx/conf/nginx.conf is as follows

user nginx;
worker_processes 1;

error_log /var/log/nginx/error.log warn;
pid /var/run/nginx.pid;

events {
  worker_connections 1024;
}


http {
  include /etc/nginx/mime.types;
  default_type application/octet-stream;

  log_format main '$remote_addr - $remote_user [$time_local] "$request" '
           '$status $body_bytes_sent "$http_referer" '
           '"$http_user_agent" "$http_x_forwarded_for"';

  access_log /var/log/nginx/access.log main;

  sendfile on;
  #tcp_nopush on;

  keepalive_timeout 65;

  # Enable gzip
  gzip on;
  gzip_min_length 1k;
  gzip_buffers 4 16k;
  #gzip_http_version 1.0;
  gzip_comp_level 1;
  gzip_types text/plain application/x-javascript text/css application/xml text/javascript application/x-httpd-php image/jpeg image/gif image/png;
  gzip_vary off;
  gzip_disable "MSIE [1-6]\.";

  server {
    listen 80;
    server_name localhost;
    keepalive_timeout 5;
    root /usr/share/nginx/html;

    location /static/ {
      alias /usr/share/nginx/html/src/app/static/;
    }

    location / {
      # checks for static file, if not found proxy to app
      try_files $uri @flask_app;
    }

    location @flask_app {
      proxy_pass http://192.168.0.2:5000; # Published on Alibaba Cloud, the intranet IP address should be filled in
      proxy_redirect off;
      proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
      proxy_set_header Host $http_host;
      proxy_set_header X-Real-IP $remote_addr;

      #proxy_buffers 8 32k;
      #proxy_buffer_size 64k;

    }
  }


}

Start the deployment

  1. Enter the docker-flie directory cd docker-flie
  2. Start docker docker-compose up
  3. View container status docker ps
  4. Enter 127.0.0.1 in the local deployment browser

Finally, three containers similar to docker_file_nginx_1, docker_file_mongo_1, and docker_file_flask_1 appear, indicating success! ! !

Pitfalls and complaints

1 The initialization file in the mongol container needs to be placed in the docker-entrypoint-initdb.d directory

I have tried the following and it shows that mongdb is not started.

ADD setup.sh /data/setup.sh
RUN chmod +x /data/setup.sh
CMD ["/data/setup.sh"]

2 The flask application cannot connect to mongo. This article uses the link method.

The database configuration should be written accordingly:

MONGODB_SETTINGS = {
    'db': 'test',
    'host': 'mongo', # 127.0.0.1 host address must be the name of the --link you configured 'username': 'test',
    'password': 'test',
    'port': 27017
  }

Change back to 127.0.0.1 during local testing

3 The proxy mode used in nginx configuration, where the IP that executes the flask application should be the intranet IP

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Analysis of table names and parent class related issues of custom model classes in Flask and Django frameworks
  • Docker deployment of Flask application implementation steps
  • How to deploy flask application to server
  • Example of how to deploy a Flask project with uWSGI and Nginx
  • CentOS7 deployment Flask (Apache, mod_wsgi, Python36, venv)
  • Python project migration and deployment based on Flask framework configuration dependency package information
  • How to deploy the flask project on CentOS
  • CentOS 7.0 uses Nginx to deploy flask application tutorial
  • Alibaba Cloud Deployment of Ubuntu 1.4 Flask + WSGI + Nginx Detailed Explanation
  • Deploy the flaskblog application on a DigitalOcean server
  • Tutorial on deploying Nginx, FastCGI and Flask framework on Mac OS
  • Tutorial on deploying Python's Flask framework on Docker
  • How to deploy a model as a service using flask

<<:  Use JavaScript to create page effects

>>:  Detailed explanation of the solution for migrating antd+react projects to vite

Recommend

Detailed explanation of the solution to permission denied in Linux

Permission denied: The reason for this is: there ...

How to use React forwardRef and what to note

Previously, react.forwardRef could not be applied...

Linux CentOS MySQL database installation and configuration tutorial

Notes on installing MySQL database, share with ev...

Native JS encapsulation vue Tab switching effect

This article example shares the specific code of ...

MYSQL slow query and log example explanation

1. Introduction By enabling the slow query log, M...

Detailed explanation of the benefits of PNG in various network image formats

BMP is an image file format that is independent o...

Detailed explanation of Mencached cache configuration based on Nginx

Introduction Memcached is a distributed caching s...

Complete steps to build NFS file sharing storage service in CentOS 7

Preface NFS (Network File System) means network f...

Solution to blank page after Vue packaging

1. Solution to the problem that the page is blank...

CSS3 flexible box flex to achieve three-column layout

As the title says: The height is known, the width...

jQuery plugin to achieve image comparison

This article example shares the specific code of ...

Code analysis of user variables in mysql query statements

In the previous article, we introduced the MySQL ...

Implementation of the login page of Vue actual combat record

Table of contents 1. Preliminary preparation 1.1 ...

Practical TypeScript tips you may not know

Table of contents Preface Function Overloading Ma...