Restrict Internet Access - Docker Container

As found here, I got this to work with docker-compose. Save as docker-compose.yml:

version: '3'

services:
  outgoing-wont-work:
    image: alpine
    networks:
      - no-internet
    command: ping -c 3 google.com # will crash

  internal-will-work:
    image: alpine
    networks:
      - no-internet
    command: ping -c 3 internal-and-external

  internal-and-external:
    image: alpine
    networks:
      - no-internet
      - internet
    command: ping -c 3 google.com

networks:
  no-internet:
    driver: bridge
    internal: true
  internet:
    driver: bridge

Then run docker-compose up -d, docker-compose ps will show something like this after a few seconds:

              Name                            Command               State    Ports
----------------------------------------------------------------------------------
dco_inet_internal-and-external_1   ping -c 3 google.com             Exit 0        
dco_inet_internal-will-work_1      ping -c 3 internal-and-ext ...   Exit 0        
dco_inet_outgoing-wont-work_1      ping -c 3 google.com             Exit 1      

Network creation for access internet

docker network create --subnet=172.19.0.0/16 internet

Network creation for block internet access

docker network create --internal --subnet 10.1.1.0/24 no-internet

If you want to connect docker container into internet

docker network connect internet container-name

If you want to block internet access

docker network connect no-internet container-name

Note

in internal network we can't expose ports to connect outside world, please refer this question for more details