search
HomeOperation and MaintenanceNginxHow nginx implements database port forwarding

How nginx implements database port forwarding

May 12, 2023 pm 11:13 PM
nginxdatabase

Due to data security considerations, under normal circumstances, the website or project database is generally prohibited from accessing the external network, or only allows access to some hosts. So, how can we allow other hosts that are prohibited from accessing to access this database without modifying such permissions? At this time, the role of Nginx is reflected.

1, mysql as an example

Oracle, sqlserver and other database configurations are the same as the following configurations, except that the database ports are different
It should be noted that this configuration must be written outside http

#使用nginx做数据库端口转发
stream {
    upstream sql {   
    # 配置数据库的ip和端口
        server 172.16.8.190:3306 weight=1 max_fails=2 fail_timeout=30s;   
    }
    server {
     # 配置本机暴露端口
       listen     925;
       proxy_connect_timeout 1s;
       proxy_timeout 3s;
       proxy_pass sql;
    }
}

2. The complete configuration is as follows

#user  nobody;#配置用户或者用户组,默认为nobody
worker_processes  2;#允许生成的进程数,默认为1

#制定日志路径,级别。这个设置可以放入全局块,http块,server块,
#级别以此为:debug|info|notice|warn|error|crit|alert|emerg
#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

#pid        logs/nginx.pid;#指定nginx进程运行文件存放地址


events {
    worker_connections  1024;    #最大连接数,默认为512
    accept_mutex on;   #设置网路连接序列化,防止惊群现象发生,默认为on
    multi_accept on;  #设置一个进程是否同时接受多个网络连接,默认为off
    #use epoll;      #事件驱动模型,select|poll|kqueue|epoll|resig|/dev/poll|eventport
}

stream {
    upstream sql {   
        server 172.16.8.190:3306 weight=1 max_fails=2 fail_timeout=30s;   
    }
    server {
       listen     925;
       proxy_connect_timeout 1s;
       proxy_timeout 3s;
       proxy_pass sql;
    }
}

http {
    include       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  logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    #keepalive_timeout  0;
    keepalive_timeout  65;

    #gzip  on;

    #配置tomcat的IP地址和访问端口
    upstream tomcat {
        server 172.16.8.190:8080;
        
     }
    
    server {
        listen       9008;
        server_name  172.16.8.190;
    #header name含下划线
    underscores_in_headers on; 
    #charset gbk; # 编码设置
    #开启gzip压缩
        #gzip模块设置
        gzip on; #开启gzip压缩输出
        gzip_min_length 1k; #最小压缩文件大小
        gzip_buffers 4 16k; #压缩缓冲区
        gzip_http_version 1.0; #压缩版本(默认1.1,前端如果是squid2.5请使用1.0)
        gzip_comp_level 2; #压缩等级
        gzip_types text/plain application/x-javascript text/css application/xml;
        #压缩类型,默认就已经包含text/html,所以下面就不用再写了,写上去也不会有问题,但是会有一个warn。
        gzip_vary on;
        #charset koi8-r;
        #charset utf-8,gbk; # 避免中文乱码
        #root    D:/htmlPage/dist; 
        #access_log  logs/host.access.log  main;
    location /{
        #这个地方指定被访问的文件夹位置
        root   D:/htmlPage;
        index  index.html index.htm;
        #limit_rate 1280k; #限制速度
        client_max_body_size  100M;
        allow all;
        autoindex on;
        proxy_set_header X-Real-IP  $remote_addr;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        add_header 'Access-Control-Allow-Headers' 'Content-Type';
        add_header 'Access-Control-Allow-Methods' 'GET';
        add_header 'Access-Control-Allow-Methods' 'POST';
        add_header 'Access-Control-Allow-Credentials' 'true';
        add_header 'Access-Control-Allow-Origin' '*';
        proxy_connect_timeout       600s;
        proxy_read_timeout          600s;
        proxy_send_timeout          600s; 
        access_log off;
        break;
        }
     }
 }

The above is the detailed content of How nginx implements database port forwarding. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
NGINX's Impact: Web Servers and BeyondNGINX's Impact: Web Servers and BeyondMay 06, 2025 am 12:05 AM

NGINX initially solved the C10K problem and has now developed into an all-rounder who handles load balancing, reverse proxying and API gateways. 1) It is well-known for event-driven and non-blocking architectures and is suitable for high concurrency. 2) NGINX can be used as an HTTP and reverse proxy server, supporting IMAP/POP3. 3) Its working principle is based on event-driven and asynchronous I/O models, improving performance. 4) Basic usage includes configuring virtual hosts and load balancing, and advanced usage involves complex load balancing and caching strategies. 5) Common errors include configuration syntax errors and permission issues, and debugging skills include using nginx-t command and stub_status module. 6) Performance optimization suggestions include adjusting worker parameters, using gzip compression and

Nginx Troubleshooting: Diagnosing and Resolving Common ErrorsNginx Troubleshooting: Diagnosing and Resolving Common ErrorsMay 05, 2025 am 12:09 AM

Diagnosis and solutions for common errors of Nginx include: 1. View log files, 2. Adjust configuration files, 3. Optimize performance. By analyzing logs, adjusting timeout settings and optimizing cache and load balancing, errors such as 404, 502, 504 can be effectively resolved to improve website stability and performance.

Deploying Applications with NGINX Unit: A GuideDeploying Applications with NGINX Unit: A GuideMay 04, 2025 am 12:03 AM

NGINXUnitischosenfordeployingapplicationsduetoitsflexibility,easeofuse,andabilitytohandledynamicapplications.1)ItsupportsmultipleprogramminglanguageslikePython,PHP,Node.js,andJava.2)Itallowsdynamicreconfigurationwithoutdowntime.3)ItusesJSONforconfigu

NGINX and Web Hosting: Serving Files and Managing TrafficNGINX and Web Hosting: Serving Files and Managing TrafficMay 03, 2025 am 12:14 AM

NGINX can be used to serve files and manage traffic. 1) Configure NGINX service static files: define the listening port and file directory. 2) Implement load balancing and traffic management: Use upstream module and cache policies to optimize performance.

NGINX vs. Apache: Comparing Web Server TechnologiesNGINX vs. Apache: Comparing Web Server TechnologiesMay 02, 2025 am 12:08 AM

NGINX is suitable for handling high concurrency and static content, while Apache is suitable for dynamic content and complex URL rewrites. 1.NGINX adopts an event-driven model, suitable for high concurrency. 2. Apache uses process or thread model, which is suitable for dynamic content. 3. NGINX configuration is simple, Apache configuration is complex but more flexible.

NGINX and Apache: Deployment and ConfigurationNGINX and Apache: Deployment and ConfigurationMay 01, 2025 am 12:08 AM

NGINX and Apache each have their own advantages, and the choice depends on the specific needs. 1.NGINX is suitable for high concurrency, with simple deployment, and configuration examples include virtual hosts and reverse proxy. 2. Apache is suitable for complex configurations and is equally simple to deploy. Configuration examples include virtual hosts and URL rewrites.

NGINX Unit's Purpose: Running Web ApplicationsNGINX Unit's Purpose: Running Web ApplicationsApr 30, 2025 am 12:06 AM

The purpose of NGINXUnit is to simplify the deployment and management of web applications. Its advantages include: 1) Supports multiple programming languages, such as Python, PHP, Go, Java and Node.js; 2) Provides dynamic configuration and automatic reloading functions; 3) manages application lifecycle through a unified API; 4) Adopt an asynchronous I/O model to support high concurrency and load balancing.

NGINX: An Introduction to the High-Performance Web ServerNGINX: An Introduction to the High-Performance Web ServerApr 29, 2025 am 12:02 AM

NGINX started in 2002 and was developed by IgorSysoev to solve the C10k problem. 1.NGINX is a high-performance web server, an event-driven asynchronous architecture, suitable for high concurrency. 2. Provide advanced functions such as reverse proxy, load balancing and caching to improve system performance and reliability. 3. Optimization techniques include adjusting the number of worker processes, enabling Gzip compression, using HTTP/2 and security configuration.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

DVWA

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 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor