Docker Community Forums

Share and learn in the Docker community.

Docker - access container only by specific IP

I want to configure my network in Docker which allow to connect to container only by using specific IP.

My problem is that I configured network in my docker-compose file and I can connect to mysql container for example using MySQL Workbench with 172.28.1.2:3306 and also with 127.0.0.1:3306. It’s possible to configure that I can connect to that container only by using 172.28.1.2:3306??

version: "3.3"

services:
    apache:
        container_name: apache
        build: ./bin/apache
        restart: always
        ports:
            - "80:80"
        networks:
            backend:
                ipv4_address: 172.28.1.1
        volumes:
            - ./wordpress/:/var/www/html/wordpress/
    mysql:
        container_name: mysql
        build: ./bin/mysql
        restart: always
        ports:
            - "3306:3306"
        networks:
            backend:
                ipv4_address: 172.28.1.2
        environment:
            MYSQL_ROOT_PASSWORD: root
            MYSQL_DATABASE: wordpress
            MYSQL_USER: admin
            MYSQL_PASSWORD: admin
        volumes:
            - sql:/var/lib/mysql

networks:
    backend:
        ipam:
            driver: default
            config:
                - subnet: 172.28.0.0/16
volumes:
    sql:

Thanks in advance for any answer.

Hello lukasz1989,

According to the documentation, compose sets up a single network for your app and each container for a service joins the default network and is both reachable by other containers on that network, and discoverable by them at a hostname identical to the container name.

So, I think you only to setup ports configuration.

Best regards,
Fouscou B.

You are confusing two topics.
1… a static ip for the container - usualy services inside a container are bound to all ips
2… binding a published port to a host ip: replace - "3306:3306" with - {an ip valid for your host}:3306:3306