You have MySQL running in a Docker Container on a Host.
Different scenario's to connect to that MySQL Database:
From an App in another Container started in the same docker-compose.yml
If you started an App in the same docker-compose.yml and want to connect to the MySQL Database:
Use the Service as the Hostname because docker-compose has its own network and will translate the servicename to to right container
version: '3.9'
services:
mydb:
image: mysql:latest
volumes:
- "./.mysql-data/db:/var/lib/mysql"
restart: always
environment:
MYSQL_DATABASE: mysqldb
MYSQL_USER: root
MYSQL_PASSWORD: root
myapp:
....
In myapp you connect to MySQL with mysql://mydb:3306/....
No Ports section!! This is because MySQL itself publishes port 3306, so no Ports section needed in docker-compose.
From an App in another Container started in another Docker command
Suppose your App is started on the same Host but in another Docker command (or in another docker-compose.yml file)
Then you need to access the database via the Host published port. But there's a problem since you cannot access the host from within a Docker Container. (At least not in a stable way, so I leave out the hacky solutions you see here on StackOverflow)
Just create a (sub)domain and point it to your Host.
And make small change in your docker-compose.yml file: Add a Ports section:
ports:
- 3333:3306
The database can be found on mysql://subdomain:3333/.....
From an App running somewhere else on another Host.
This is the same as the previous solution:
- Create subdomain
- Publish the port
- Connect to that subdomain
From Docker Container on Host to MySQL on another Server (not in Docker)
Again, same as before
- Create subdomain
- Publish the port on the Host
- Connect to that subdomain
Solution with the subdomain need a ProxyServer?
In case your host also answers other requests from outside, you might need a ProxyServer (Nginx?) to route the 3333 traffic to port 3306 in the container.
And if you do have that ProxyServer, you don't need the Ports section anymore.
Answer to the question in the Problem Description
You want to connect to a MySQL database running on some AWS host.
That database is already running. It has a host, username, password.
Why are you starting a new Docker Container with MySQL Image?
Only thing you should start is that 'sampleapp' container with software connecting to the external MySQL.
I don't understand why you start a MySQL Container again if you already have an external one running on AWS.