Skip to content

Instantly share code, notes, and snippets.

@pangyuteng
Last active February 13, 2024 18:46
Show Gist options
  • Save pangyuteng/b9f61fc7adc409c5f932e6a837d7b7dd to your computer and use it in GitHub Desktop.
Save pangyuteng/b9f61fc7adc409c5f932e6a837d7b7dd to your computer and use it in GitHub Desktop.
how to access local port with an active ufw from within a container
how to access local port with an active ufw from within a container

main solution

TLDR: specify network subnet in compose file, then allow in ufw.

  • in docker-compose setup network with specified subnet.
  • in docker-compose add below to access localhost via host.docker.internal.
myservice:
    extra_hosts:
        - "host.docker.internal:host-gateway"
  • allow subnet in ufw sudo ufw allow from 172.18.0.1/16
  • in container, call directly docker exec test-curl-1 curl host.docker.internal:8112
  • ??? setup socat, don't really think this is necessary unless you are routing sockets. docker exec test-curl-1 curl proxy:8112

alternatively, use network_mode: host

-- ref


https://gist.github.com/lalyos/09c0e6131b9de8240eb7
https://github.com/docker/compose/issues/4336
https://stackoverflow.com/questions/24319662/from-inside-of-a-docker-container-how-do-i-connect-to-the-localhost-of-the-mach
https://forums.docker.com/t/how-to-reach-localhost-on-host-from-docker-container/113321/16
https://github.com/moby/moby/pull/42785
https://stackoverflow.com/questions/46845381/how-do-configure-docker-compose-to-use-a-given-subnet-if-a-variable-is-set-or-c
https://docs.docker.com/compose/networking/
https://superuser.com/questions/1709013/enable-access-to-host-service-with-ubuntu-firewall-from-docker-container

version: '3.7'
services:
proxy:
#??? image: docker-friendly
#??? command: TCP-L:2375,fork UNIX:/var/run/docker.sock
#volumes:
# - /var/run/docker.sock:/var/run/docker.sock
image: bobrik/socat
restart: always
command: TCP4-LISTEN:8112,fork,reuseaddr TCP4:host.docker.internal:8112
extra_hosts:
- "host.docker.internal:host-gateway"
expose:
- 8112
networks:
default:
curl:
extra_hosts:
- "host.docker.internal:host-gateway"
image: curlimages/curl
restart: always
command: "sleep 1000"
networks:
default:
networks:
default:
driver: bridge
ipam:
driver: default
config:
- subnet: 172.18.0.0/16
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment