###### tags: `Docker` `MySQL` # MySQL Port public access closure without overriding docker iptable forwarding rules This page is the reminder notes for me if someone setup the docker container of MySQL not correctly, you can't block it in multiple offical way in some reason, like if it is not done and follow by you, and it accident roar for it, there is bunch of sh*t already turns on and running, you don't have time to check it one by one but you need to block it or else the mySQL port will be publiclly accessable problem in the network restricted envoriment, then this guide will save your life. ## Offical way to do so before the docker is up Normal I would recommend you to do it in offically way by creating a network rules first before eveything, making rules is very important as if there are bunch of containers, you won't want to amended their network setting one by one if they are sharing some same network rules. By doing so, first create a network allow to access the internet but expose the ports internally: ``` docker network create --subnet=172.19.0.0/16 internet ``` Adding this IPTable rules would be recommend also: ``` sudo iptables --insert DOCKER-USER -s 172.19.0.0/16 -j REJECT --reject-with icmp-port-unreachable sudo iptables --insert DOCKER-USER -s 172.19.0.0/16 -m state --state RELATED,ESTABLISHED -j RETURN ``` Then create a rule which will block the internet access: ``` docker network create --internal --subnet 10.1.1.0/24 no-internet ``` After that, you can block the container internet access or allow it by rules, for example, to block one of the container's internet accessing: ``` docker network connect no-internet container-name ``` You may want to check out **docker network** for details as it is crazily useful and important when you setup the docker. For more docker network related information: https://docs.docker.com/network/ ## Quick way to block it But sometimes there is one of them having problem, and you have tons of reason need to solve it immediantly, then you can do the below step some blocking the specific port. ### Step 1: Find the contiainer ID of mysql ``` sudo docker ps ``` ### Step 2: Stop the docker container ``` sudo docker stop <container ID> ``` ### Step 3: Edit the related container host config file #### 3.1 First confirm the container full ID related folder Matching the container ID by first 12 char with the folder ``` sudo ls /var/lib/docker/containers/ ``` #### 3.2 Edit the related JSON file ``` sudo vi /var/lib/docker/containers/{container_id}/hostconfig.json ``` #### 3.3 Found the related config part as below ``` ....... "PortBindings": { "3306/tcp": [ { "HostIp": "", "HostPort": "3306" } ] }, ....... ``` Amened the Host IP as ``` "HostIp": "127.0.0.1" ``` Then save the file and quit ### Step 4: Restart Docker to clear Docker engine cache ``` sudo systemctl restart docker ``` ### Step 5: Restart the mySQL container ``` sudo docker start {container_id} ```