Write down Docker Compose file for C#.net  and MySQL application

Write down Docker Compose file for C#.net and MySQL application

To make a Docker Compose file for a C# .NET app with a MySQL database, follow this example. This is for a basic C# .NET app that connects to a MySQL database.

  1. C# .NET Application (app/Program.cs):
using System;
using MySql.Data.MySqlClient;

class Program
    static void Main()
        string connectionString = "Server=mysql;Port=3306;Database=mydatabase;User=myuser;Password=mypassword;";

        using MySqlConnection connection = new MySqlConnection(connectionString);

        using MySqlCommand command = new MySqlCommand("SELECT 'Hello from MySQL'", connection);
        using MySqlDataReader reader = command.ExecuteReader();

        while (reader.Read())
  1. Dockerfile (app/Dockerfile):
FROM mcr.microsoft.com/dotnet/sdk:6.0 AS build

COPY . .
RUN dotnet publish -c Release -o out

FROM mcr.microsoft.com/dotnet/runtime:6.0
COPY --from=build /app/out .

CMD ["dotnet", "app.dll"]
  1. Docker Compose file (docker-compose.yml):
version: '3'
      context: ./app
      dockerfile: Dockerfile
      - mysql
    image: mysql:latest
      MYSQL_ROOT_PASSWORD: myrootpassword
      MYSQL_DATABASE: mydatabase
      MYSQL_USER: myuser
      MYSQL_PASSWORD: mypassword

In this example:

  • The C# .NET app is built with the .NET SDK in the first stage of the Dockerfile and then run using the .NET runtime in the second stage.

  • The MySQL service uses the official MySQL image from Docker Hub. Environment variables are set to set up the MySQL instance (root password, database, user, and password).

  • The depends_on command in the app service makes sure the C# .NET app container waits for the MySQL container to be ready before starting.

To run the application, navigate to the directory containing the docker-compose.yml file and run:

docker-compose up

This will start the services you set up. The .NET app connects to the MySQL database with the given credentials.

Remember: Change placeholder values (like myrootpassword, mydatabase, myuser, and mypassword) to your preferred settings. Also, adjust the C# .NET app and Dockerfile based on your project's structure and needs.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!