1

I want to connect my application with MySQL by Docker-compose. But, when I go to https://localhost:5001/api/Contacts (my Api), it fails to connect to database (Error: ERR_SSL_PROTOCOL_ERROR).
Here is my Docker-compose:

services:
  mysql:
    image: mysql
    restart: always
    volumes:
      - ./setup.sql:/docker-entrypoint-initdb.d/setup.sql
      - dbdata:/var/lib/mysql
    environment:
      MYSQL_ROOT_USER: root
      MYSQL_ROOT_PASSWORD: admin
    ports:
      - 3307:3306

  webapi:
    image: webapi
    build: .
    restart: always
    depends_on:
      - mysql
    ports:
      - 5001:80

volumes:
  dbdata:

Here is my Startup.cs:

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<DotnetCoreTrainingContext>(options =>
        .UseMySql(Configuration.GetConnectionString("DefaultConnection"), 
        new MySqlServerVersion(new Version())));
    services.AddControllers();
}

Here is my appsettings.json:

"ConnectionStrings": {
    "DefaultConnection": "server=mysql;user=root;password=admin;port=3307;database=DotnetCoreTraining;sslmode=none;"
}

How can I set server=mysql (name of MySQL image on Docker in my computer) in ConnectionStrings?

1 Answer 1

1

When you're connecting from another container on the bridge network created by docker-compose, you connect using the port the container is listening on. The mapped port is used when you connect from the host machine.

In your case that means that you need to connect on port 3306 and your connection string should be

server=mysql;user=root;password=admin;port=3306;database=DotnetCoreTraining;sslmode=none;
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you for your answer. But port 3306 is in use so in the Docker-compose file, I setting port is 3307. When running local environment, I setting server=localhost;user=root;password=admin;port=3307;database=DotnetCoreTraining;sslmode=none;, it can connect to mysql. But I build Docker file and build project, run image project to run container, now it's not working. What's up?
I didn't ask you to change the port mapping to 3306. Just leave it as it is and change the connection string. Your webapi container is on the same bridge network as the database, so it doesn't use the port mapping at all. It connects directly to the database container and the container is listening on port 3306.
Thank you very much. It can fix my error with ConnectionStrings: is server=mysql;user id=root;password=admin;port=3306;database=DotnetCoreTraining;

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.