Docker-compose MySQL container access from another container
I am relatively new to docker and I’m trying to create a development environment my C# project with a MySQL server and database.
I already have my C# console project Dockerfile and also a docker-compose file that has a service to my project and a service for a MySQL server. The problem is, from my C# console project, I can’t access the MySQL server from that container using the service name or the container_name
if set.
There is my docker-compose.yml
file:
version: '3.5'
services:
databasetester:
image: ${DOCKER_REGISTRY-}databasetester
build:
context: .
dockerfile: src/DatabaseTester/Dockerfile
depends_on:
- db
db:
image: mysql:5.7
restart: always
environment:
MYSQL_DATABASE: testdb
MYSQL_USER: testusr
MYSQL_PASSWORD: testpwd
MYSQL_ROOT_PASSWORD: testroot
ports:
- "3307:3306"
expose:
- 3307
volumes:
- ./bin/_database:/var/lib/mysql
Also, in my project I am using EntityFrameworkCore to access the database:
public class DatabaseContext : DbContext
{
public DbSet<CharacterEntity> Characters { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseMySql("Server=db;Uid=testusr;Pwd=testpwd;Database=testdb;Port=3307");
base.OnConfiguring(optionsBuilder);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
}
public class CharacterEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
When I start the project, it throws an error while trying to connect to the mysql server:
An exception has been raised that is likely due to a transient failure. Consider enabling transient error resiliency by adding ‘EnableRetryOnFailure()’ to the ‘UseMySql’ call.
Unable to connect to any of the specified MySQL hosts.
I tried to follow many tutorials and guides and they are all using the service name has a "server" in the mysql connection string, but in my case it doesn’t seem to work.
Do you have any ideas how I can solve this issue?
Source: Docker Questions