Home > other >  How to proxy HTTP request from container to a specific address(:port) in docker?
How to proxy HTTP request from container to a specific address(:port) in docker?

Time:10-10

I am currently creating a tool to manage docker containers.
So I am looking for a way to connect to an api server in lan from within the container.
There are several api servers, running on different hosts.
The api server is not on port 80, but on a random port at startup.
To use the api, you need to specify a token in the Authorization header.
However, it is not possible to include the token in the container in this situation.
To use api from within the container, I want to route 192.168.0.2:49152 to api.example.com:80.

I have done the following.

docker run -it \
  --add-host=api.example.com:192.168.0.2 \
  image:version main.sh

We decided that it was not possible to attach a port or Token to the above command, so we did the following.

docker run -it \
  --add-host=api.example.com:192.168.0.10 \
  --env HTTP_PROXY="http://host.docker.internel:49513" \
  image:version main.sh

As you can see above, I thought of having a proxy server attached to the tool.
The proxy server listens on a port like 49513.
The proxy server comes with Authorization and relays the request to the api in the container.

The problem with this implementation was that it proxied all HTTP communication.
If all HTTP communication is proxied, there will be a lag in communication that requires real-time performance.
Since this tool manages a large number of containers, this issue is considered critical.
There is NO_PROXY in docker's Proxy, but there was no whitelisting of proxies like YES_PROXY which is the opposite of this.

I'm thinking of extending the above implementation. Please let me know if you have any good ideas.

I am using a translator, so if you have any questions, please comment and I will do my best to answer them. If you have any questions or comments, please comment to me.

Thank you.

CodePudding user response:

You can configure the proxy server to be a transparent http proxy server

Assuming proxy server IP is 192.168.0.20, API server IP is 192.168.0.10

docker run -it \
  --add-host=api.example.com:192.168.0.20 \
  image:version main.sh

Configure proxy server using nginx

server {
     listen  80;
     server_name api.example.com;

     location / {
         proxy_pass http://192.168.0.10:xxx;
         proxy_set_header Host $host;
     }
 }

In this way, only requests to api.example.com are sent to the proxy server.

  • Related