Nginx: forwarding TCP traffic

1. Scene introduction

Recently, when using a Docker container to deploy a proxy application, I found that the application listens to the address 127.0.0.1:1080, so normally only local programs can use the proxy, but what is actually needed is that both LAN and public network users can access use.

2. Solutions

The protocol used by the proxy application is http/sock , so it only needs to forward the TCP traffic of the external network to the local port 1080. Nginx supports forwarding http traffic and tcp traffic, so Nginx is used here to solve it.

1. Environment installation

Install Nginx, the image used by the container is Alpine, and the provided package management tool is apk, just install it according to your own system tools

apk add nginx

Install the stream module

apk add nginx-mod-stream

2. Configuration file

Since TCP traffic is forwarded, the stream item is configured.

Open the /etc/nginx/conf.d/stream.conf file and modify the content as follows:

# /etc/nginx/conf.d/stream.conf

stream {
	# Specifies the main log format.
	log_format main '$remote_addr [$time_local] '
			'$protocol $status $bytes_sent $bytes_received '
			'$session_time "$upstream_addr" '
			'"$upstream_bytes_sent" "$upstream_bytes_received" "$upstream_connect_time"';

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

	# Includes servers configs.
	include stream.d/*.conf;
	
    #本地运行的服务
    upstream tcp_backend { 
        server 127.0.0.1:1080; 
    }
    server { 
        listen 10000; 
        proxy_pass tcp_backend;
    }
}

The above configuration file will listen to port 10000 , and then forward the TCP traffic of this port to 127.0.0.1:1080 . It can also be seen from here that Nginx also supports forwarding traffic to any service address, which is configured here as the address you need That's it.

3. Run the service

Check whether the configuration file is correct, execute the following command:

nginx -t

Start or restart the service

nginx

nginx -reload

At this point, the external network can access the 127.0.0.1:1080 application service.

Guess you like

Origin blog.csdn.net/wsfsp_4/article/details/128664620