Search code examples
linuxdockerproxytor

How do I connect a docker container to tor proxy on local machine?


I want to ping a website from inside my docker container through tor proxy on my local machine. Without setting the proxy, I could not be able to ping. When I run my container with:
sudo docker run --rm -it -p9150:9150 my-container
I got the following error:
Error starting userland proxy: listen tcp 0.0.0.0:9150: bind: address already in use.
I started tor-browser on my localhost:9150 but I can't do port-forwarding when running a container. Also I don't want to use --net=host in command. I added the following line
Environment="ALL_PROXY=socks5://127.0.0.1:9150" to /lib/systemd/system/docker.service but it didn't word. Anyone can help me with this? (OS: Ubuntu 20.04)


Solution

  • To run the TOR proxy and the app

    After a long research I did, I came up to the following steps:

    1. sudo docker pull dperson/torproxy
    2. sudo docker network create tor
    3. sudo docker run --rm -it --name mytor --network tor -p9050:9050 dperson/torproxy
    4. sudo docker run --rm -it --network tor myapp

    Inside myapp I have a python script which sends message to my telegram channel through tor socks proxy. I have a network (tor) and both containers see each other through it. In the python script I have the following line:

    bot = telegram.Bot(token=token, request=Request(con_pool_size=10, connect_timeout=40, proxy_url='socks5h://mytor:9050'))
    

    To manually test the TOR proxy

    Run another container, a general-purpose one like for example

    docker run --rm -it --network tor ubuntu:22.04
    

    Install curl the usual way (for example with apt-getin debian/ubuntu).

    Then inside the command line do:

    curl -x socks5://mytor:9050 http://checkip.amazonaws.com/
    

    You'll see the IP of the TOR exit node:

    IP of the TOR exit node