0

I'm trying to containerize an Asp.Net Core application using Docker but on docker compose up aspnet app logs Unable to connect to any of the specified MySQL hosts and exits. I've read that Docker uses it's own internal network and provides DNS to connect to other container, so I use mysql service name in connection string, but it still doesnt connect.
It was working, when I only used docker to run mysql container, and exposed port 3306 to host, but for some reason it doesnt work now. What am I missing?

docker-compose

version: '3'

services:
  mysql:
    image: mysql:8
    environment:
      MYSQL_DATABASE: ctox_db
      MYSQL_ROOT_PASSWORD: 019638
    volumes:
      - mysqldata:/var/lib/mysql
    networks: 
      - ctox_net  

  ctoxweb:
    build: .
    depends_on: 
      - mysql
    environment: 
      - "ConnectionStrings:AppContext=server=mysql; port=3306; database=ctox_db; user=root; password=019638"
    links:
      - mysql  
    networks: 
      - ctox_net  

volumes:
  mysqldata:      

networks:
  ctox_net:
    driver: bridge  


Startup.cs

public void ConfigureServices(IServiceCollection services)
{
    // other services ...
    var appContextConnection = Configuration.GetConnectionString("AppContext");
    services.AddDbContext<AppDbContext>(options =>
        options
            .UseLazyLoadingProxies()
            .UseMySql(appContextConnection, ServerVersion.AutoDetect(appContextConnection)));
}


PS I added environment variables to configuration, connection string is pulled correctly.

1 Answer 1

1

It turns out that the problem was not in the docker-compose or web app but in the mysql container. I thought that depends_on would magically wait for mysql server to start and be ready to receive connections, however as documentations suggests (Control startup) developer should rather depend on application itself to wait for database and try to reestablish connection.

For someone who needs a quick fix that might be acceptable on small projects (be aware, it's not recommended) just add restart: on-failure to your web app in docker-compose file

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.