gelveri
gelveri

Reputation: 21

docker restrict container network access

I created 2 containers on docker. These containers of mine are in the same network. I want to restrict these containers from accessing my local network.

For example; container 1 can access my entire network. but container 2 can't reach anywhere but only I can access it. I can't do this from my central firewall because the source address of all containers is my docker host's IP address.

I tried doing this with iptables. I added the following rule for container 1:

iptables -I DOCKER-USER -s 172.17.0.2 -j ACCEPT

and I added the following rule for container 2:

iptables -I DOCKER-USER -s 172.17.0.4 -j DROP

When I do this, container 1 can access my network, container 2 cannot access my network. This is what I want. But as such, container 2 cannot respond to my TCP requests, so I cannot reach it.

Is there a solution to this?

Upvotes: 2

Views: 2653

Answers (1)

DCCoder
DCCoder

Reputation: 1628

It sounds like what you are looking for is an internal network. An internal network explicitly restricts external access to the network.

How you put this into play ultimately depends on how you are deploying your containers. If you are using docker-compose then you would need to modify your docker-compose.yml file to look something like this:

version: '2'
services:
  app1:
    image: mysql:5.7
    networks:
      - network1 
        
  app2:
    image: someImage
    networks:
      - network1
      - network2
networks:
  network1:
    internal: true
  network2:

If you are going through the command line then you would create a network like this:

docker network create -d overlay --internal myprivatenetwork

and then attach it to your container in this manner:

docker network connect myprivatenetwork app1

If you are looking for something to work across swarms then an overlay network may possibly be better suited for your needs. Per the documentation:

The overlay network driver creates a distributed network among multiple Docker daemon hosts. This network sits on top of (overlays) the host-specific networks, allowing containers connected to it (including swarm service containers) to communicate securely when encryption is enabled.

An overlay network is created in the following manner

docker network create -d overlay --attachable my-attachable-overlay

And can be attached in the same was as mentioned above.

Upvotes: 2

Related Questions