Reputation: 7909
I have a binary that listens on port 3000
, however, Google Cloud Run wants me to listen on the port defined by $PORT
, that defaults to 8080
.
Is there a way to make my container bind to 8080 and then forward the incoming requests to 3000? for examplem by adding a short script and one line to my Dockerfile
, it would make my container listen on 8080 and forward to my binary.
Upvotes: 3
Views: 1679
Reputation: 3498
If you can install a run a second process and start it along your main process then install and run socat using the following command:
socat tcp-listen:8080,fork,reuseaddr tcp-connect:localhost:3000
This way socat will bind to the 8080 port and send all the traffic to the port 3000 where your binary is listening.
Outside of Cloud Run: If you cannot touch your image nor your container then you can still run socat on an additional container, for example:
version: '3.5'
services:
proxy:
image: alpine/socat:1.0.3
command: tcp-listen:8080,fork,reuseaddr tcp-connect:myservice:3000
networks:
- mynet
networks:
mynet:
external: true
Where mynet
is the network where your binary is running and myservice
is the service name of your binary.
Upvotes: 1
Reputation: 26997
The code below is untested, but the general idea is this:
In the Dockerfile, replace the ENTRYPOINT
with a startup script:
FROM debian:9 # or another container that has iptables available
RUN apt-get install iptables
EXPOSE 8080
ENTRYPOINT /bin/startup.sh /bin/original
And then write a startup script that enables iptables and forwards inbound traffic on 8080 to 3000 inside the container:
#!/usr/bin/env bash
set -e
sed -i 's/#net.ipv4.ip_forward=1/net.ipv4.ip_forward=1/g' /etc/sysctl.conf
sysctl -p
systemctl start iptables
iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 8080 -j REDIRECT --to-port 3000
iptables -t nat -A PREROUTING -i eth0 -p udp --dport 8080 -j REDIRECT --to-port 3000
unshift
exec "$@"
Upvotes: 2