I am using Docker Desktop on Mac.
I launched my MariaDB database container by docker-compose:
version: '3'
volumes:
data:
services:
db:
image: mariadb
environment:
MYSQL_ROOT_PASSWORD: password
MYSQL_DATABASE: mydb
MYSQL_USER: user
MYSQL_PASSWORD: password
volumes:
- data:/var/lib/mysql
ports:
- "3306:3306"
Then, I spin up it via docker-compose up -d
. The db
container runs fine.
On my local machine (outside local Docker environment), I would like to access this db
container, I wonder whether I can use localhost
to access the database running inside Docker container.
So, I verified it via my spring boot application which is directly running on my local machine not in container, I defined datasource as DATASOURCE_URL=jdbc:mariadb://localhost:3306/mydb
My local application is able to establish the connection. But it confuses me, shouldn’t the behaviour be that only containers in the same docker network can access the db
container via localhost
? Could someone please elaborate & explain for me?
2
Answers
Take a closer look at your docker-compose file. You have mentioned the following ports field.
It means that you are exposing container port 3306 to host machine port 3306 (which is your mac). So, that’s why you are able to access it via
localhost
.As @Bhavadharani has mentioned:
With the line:
ports:
– "3306:3306"
You are publishing port 3306 in your local machine and it is connected to port 3306 in the container.
To be able to access port 3306 inside the docker network from another container, you don’t need to publish it on your machine. You can access it if the containers are in the same network and the local FW allows it.