Expose Docker port to specific interface

Is it possible to only expose docker ports to a specific interface without having to specify a specific IP address?

version: '2'

services:
  mosquitto:
    ports:
      - "192.168.0.1:1883:1883"

The use case is that two interfaces are connected to a RaspberryPI3, WiFi and Ethernet. One of them connects to the internet, the other to an internal network. I would like to only expose access to our Mosquitto broker to the internal network.

Because, docker create it’s own network as default. So when you expose port “1883:1338” - it’s only map the port from Host OS to container port.

In this case, if you want to specific IP address for mapping port, I think you should set config static IP address 192:168.0.1 to specific service or your Host OS.

You can read more in Docker Compose v2 - Ports for more details. Hope this will help you and pardon me if I wrong.

I am currently testing a solution proposed on StackOverflow. It basically uses the host network and then configures iptables. I’ve extended the given answer to use service variables and block everything except a specific interface:

echo "Blocking port 1883 on all interfaces except $MOSQUITTO_INTERFACE"
iptables -A INPUT -i !$MOSQUITTO_INTERFACE -p tcp --destination-port 1883 -j DROP

Hi @moritz.ulmer, did the solution from the stackoverflow thread work for you?

It did kind of. I will be separating the iptables config into two docker services, one with priveleges and the other only focusing on mosquito/MQTT.

The problem was that the docker internal dns resolution was not working between services with the docker network and the other with the host network. Also, a slight security risk to run MQTT as a privileged image.

Did that answer your question?

I sounds to me as though you’ve got some avenues to explore. Let us know here if they all turn out to be dead-ends and we’ll see if we can unblock you.

@moritz.ulmer are you still using this solution or have you find a better way?

Have you also blocked port 22222?

Sorry, I’m not using Balena any longer, so I can’t help you. Also it’s been 4-5 years ago :sweat_smile:

@moritz.ulmer thank you for your fast response.

Then my question is for those who use Balena. Is this solutions still best to solve this problem? I have a modem and a wifi ap on my board. I want wifi clients to be able to connect to one port on my single container but I don’t want to expose the port to rest of the world via the modem. Port 22222 shouldn’t be accessible at all, only in development mode.

Someone?

Hello,

If I understand correctly, you’re trying to ensure that your docker container is only accessible from one network interface? I found a couple of SO questions that might help with this:

hope it helps.