


Introduction to the application of Docker deployment of Nginx+Flask+Mongo (with code)
This article brings you an introduction to the application of Docker deployment of Nginx Flask Mongo (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Use Docker to deploy Nginx Flask Mongo application
Nginx is used as the server, Mongo is the database support, and Flask is the web framework of the Python language. Using the container features of Docker, it can be easily deployed on Linux
Project preparation on the server
The main project directory 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
Detailed configuration of Docker
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
Configuration of MongoDB
/mongo/Dockerfile The content is as follows
FROM mongo:3.6 # 设置时区 ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 设置工作目录 ENV WORKDIR /usr/local/work ENV AUTO_RUN_DIR /docker-entrypoint-initdb.d ENV INSTALL_MONGO_SHELL setup.sh RUN mkdir -p $WORKDIR # 复制数据库的初始化命令 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 give it the read and write capabilities of the database test Operation
#!/bin/bash mongo <h3 id="Flask-application-configuration">Flask application configuration</h3><p>/flask/Dockerfile content is as follows</p><pre class="brush:php;toolbar:false">FROM python:3.6 # 设置时区 ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 设置工作区 RUN mkdir -p /home/web WORKDIR /home/web # 添加依赖 ADD requirements.txt /home/web/requirements.txt RUN pip3 install -i https://pypi.douban.com/simple/ -r requirements.txt # 使用gunicorn启动应用 CMD gunicorn -w 4 -b 0.0.0.0:5000 run:app
/src/app/run.py code
here Annotated app.run() for debugging, and started with gunicorn when publishing
from app import create_app app = create_app('default') app.debug=False # if __name__ == '__main__': # app.run()
Nginx configuration
/nginx/Dockerfile content is as follows
FROM nginx:1.14 # 设置时区 ENV TZ=Asia/Shanghai RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone # 复制配置 COPY conf/nginx.conf /etc/nginx/nginx.conf
/nignx/conf The content of /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; # 开启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; # 发布在阿里云上,应填写内网IP 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 deployment
- Enter the docker-flie directory
cd docker-flie
- Start docker
docker-compose up
- View container status
docker ps
- 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! ! !
Trampling on pitfalls
- 1 The initialization file in the mongol container needs to be placed in the docker-entrypoint-initdb.d directory
I have done the following If you try, it will show 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 configuration of the database should be written accordingly:
MONGODB_SETTINGS = { 'db': 'test', 'host': 'mongo', # 127.0.0.1 host地址一定要写你配置的--link的名字 'username': 'test', 'password': 'test', 'port': 27017 }
Change back to 127.0.0.1
3 when testing locally. The proxy mode used in nginx configuration, in which the IP of the flask application is executed , should be the intranet IPThis article has ended here. For more other exciting content, you can pay attention to the mongodb video tutorial column on the PHP Chinese website!
The above is the detailed content of Introduction to the application of Docker deployment of Nginx+Flask+Mongo (with code). For more information, please follow other related articles on the PHP Chinese website!

MySQL'sBLOBissuitableforstoringbinarydatawithinarelationaldatabase,whileNoSQLoptionslikeMongoDB,Redis,andCassandraofferflexible,scalablesolutionsforunstructureddata.BLOBissimplerbutcanslowdownperformancewithlargedata;NoSQLprovidesbetterscalabilityand

ToaddauserinMySQL,use:CREATEUSER'username'@'host'IDENTIFIEDBY'password';Here'showtodoitsecurely:1)Choosethehostcarefullytocontrolaccess.2)SetresourcelimitswithoptionslikeMAX_QUERIES_PER_HOUR.3)Usestrong,uniquepasswords.4)EnforceSSL/TLSconnectionswith

ToavoidcommonmistakeswithstringdatatypesinMySQL,understandstringtypenuances,choosetherighttype,andmanageencodingandcollationsettingseffectively.1)UseCHARforfixed-lengthstrings,VARCHARforvariable-length,andTEXT/BLOBforlargerdata.2)Setcorrectcharacters

MySQloffersechar, Varchar, text, Anddenumforstringdata.usecharforfixed-Lengthstrings, VarcharerForvariable-Length, text forlarger text, AndenumforenforcingdataAntegritywithaetofvalues.

Optimizing MySQLBLOB requests can be done through the following strategies: 1. Reduce the frequency of BLOB query, use independent requests or delay loading; 2. Select the appropriate BLOB type (such as TINYBLOB); 3. Separate the BLOB data into separate tables; 4. Compress the BLOB data at the application layer; 5. Index the BLOB metadata. These methods can effectively improve performance by combining monitoring, caching and data sharding in actual applications.

Mastering the method of adding MySQL users is crucial for database administrators and developers because it ensures the security and access control of the database. 1) Create a new user using the CREATEUSER command, 2) Assign permissions through the GRANT command, 3) Use FLUSHPRIVILEGES to ensure permissions take effect, 4) Regularly audit and clean user accounts to maintain performance and security.

ChooseCHARforfixed-lengthdata,VARCHARforvariable-lengthdata,andTEXTforlargetextfields.1)CHARisefficientforconsistent-lengthdatalikecodes.2)VARCHARsuitsvariable-lengthdatalikenames,balancingflexibilityandperformance.3)TEXTisidealforlargetextslikeartic

Best practices for handling string data types and indexes in MySQL include: 1) Selecting the appropriate string type, such as CHAR for fixed length, VARCHAR for variable length, and TEXT for large text; 2) Be cautious in indexing, avoid over-indexing, and create indexes for common queries; 3) Use prefix indexes and full-text indexes to optimize long string searches; 4) Regularly monitor and optimize indexes to keep indexes small and efficient. Through these methods, we can balance read and write performance and improve database efficiency.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver Mac version
Visual web development tools
