In this tutorial, we will be learning how to isolate Docker containers using network policies. The goal is to provide an understanding of how to set up policies that restrict the network connections that containers can establish.
By the end of this tutorial, you'll have a good understanding of:
Before moving forward with this tutorial, make sure you have:
A Docker network policy is a set of rules that control the traffic flow between containers. With network policies, we can define which containers can communicate with others, effectively isolating certain containers as needed.
To create a network policy, we need to write a JSON file that defines the communications allowed between containers.
Once the network policy is defined, we can apply it to the Docker daemon using Docker commands.
{
"name": "isolated_policy",
"Description": "This policy isolates a specific container",
"ContainerSelector": { "role": "db" },
"Ingress": [
{
"Ports": [
{
"Protocol": "TCP",
"Port": "3306"
}
],
"From": [
{ "ContainerSelector": { "role": "frontend" } }
]
}
]
}
This JSON file defines a network policy called isolated_policy
, which applies to containers with the role of db
. It only allows incoming traffic (Ingress) on port 3306
from containers with the role frontend
.
$ docker network create --driver overlay --subnet=192.168.0.0/16 --gateway=192.168.0.100 --ip-range=192.168.1.0/24 my_network
$ docker network connect --ip 192.168.1.5 my_network my_container
First, we create a network with a specific subnet, gateway, and IP range. Then, we connect a container to this network with a specific IP.
In this tutorial, we learned about Docker network policies and how they're used to control the communication between containers. We also learned how to create and apply these policies.
To further your knowledge, consider exploring:
192.168.1.5
:{
"name": "ip_policy",
"Ingress": [
{
"From": [
{ "ipBlock": { "cidr": "192.168.1.5/32" } }
]
}
]
}
app
:{
"name": "block_policy",
"ContainerSelector": { "role": "app" },
"Egress": []
}