En este artículo, prepararemos el entorno para ejecutar contenedores en Windows 10 y crearemos una aplicación .NET simple en contenedores.
Para completar todos los pasos a continuación, necesita un sistema de 64 bits con la versión 2004 o posterior y compilación 18362 o posterior. Verifique la versión y el número de compilación ejecutando el comando en PowerShell winver
Si la versión es inferior a la requerida, debe actualizar y solo luego ir más allá
Instalación de WSL 2
Primero, habilitemos el componente Subsistema de Windows para Linux (WSL). Para hacer esto, inicie PowerShell con derechos de administrador y ejecute el primer comando
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
dism.exe /online /enable-feature /featurename:VirtualMachinePlatform /all /norestart
, shutdown -r -t 1
WSL 2 Linux wsl --set-default-version 2
, Linux Microsoft Store, , Ubuntu 20.04 LTS
Linux, PowerShell wsl --list --verbose
Linux, wsl --terminate Ubuntu-20.04
Linux \\wsl$
Docker
Docker Desktop Windows ,
Docker Desktop Docker Linux (WSL 2)
Docker PowerShell, Bash. docker version
, Docker , busybox,
docker run busybox echo "hello docker!!!"
. - . , rabbitmq
docker run --name rabbit1 -p 8080:15672 -p 5672:5672 rabbitmq:3.8.9-management
:
docker run
- . , Docker Hub
--name rabbit1
- rabbit1
-p 8080:15672
- . 8080 - , 15672 -
rabbitmq:3.8.9-management
- /,
RabbitMQ 5672 8080
, , docker container ls --all
docker ps -a
: docker stop rabbit1
. : docker start rabbit1
.NET
, .. , . bridge, .. , mynet bridge
docker network create mynet
redis . -d
docker run --name redis1 --network mynet -d redis
Visual Studio 2019 ASP.NET Core Web API,
Redis StackExchange.Redis Package Manager Console
Install-Package StackExchange.Redis -Version 2.2.4
,
RandomWeatherService.cs,
using System;
namespace WebApiFromDocker
{
public class RandomWeatherService
{
private Random _randomGenerator;
public RandomWeatherService()
{
_randomGenerator = new Random();
}
public int GetForecast(string city)
{
var length = city.Length;
var temperatureC = _randomGenerator.Next(-length, length);
return temperatureC;
}
}
}
RedisRepository.cs,
using StackExchange.Redis;
using System;
using System.Threading.Tasks;
namespace WebApiFromDocker
{
public class RedisRepository
{
private string _connectionString = "redis1:6379";
private TimeSpan _expiry = TimeSpan.FromHours(1);
public async Task SetValue(string key, string value)
{
using var connection = await ConnectionMultiplexer
.ConnectAsync(_connectionString);
var db = connection.GetDatabase();
await db.StringSetAsync(key.ToUpper(), value, _expiry);
}
public async Task<string> GetValue(string key)
{
using var connection = await ConnectionMultiplexer
.ConnectAsync(_connectionString);
var db = connection.GetDatabase();
var redisValue = await db.StringGetAsync(key.ToUpper());
return redisValue;
}
}
}
Startup
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<RandomWeatherService>();
services.AddScoped<RedisRepository>();
services.AddControllers();
}
, WeatherForecastController
using Microsoft.AspNetCore.Mvc;
using System;
using System.Threading.Tasks;
namespace WebApiFromDocker.Controllers
{
[ApiController]
[Route("api/[controller]")]
public class WeatherForecastController : ControllerBase
{
private RandomWeatherService _weather;
private RedisRepository _cache;
public WeatherForecastController(
RandomWeatherService weather,
RedisRepository cache)
{
_weather = weather;
_cache = cache;
}
//GET /api/weatherforecast/moscow
[HttpGet("{city}")]
public async Task<WeatherForecast> GetAsync(string city)
{
int temperatureC;
var cachedTemperatureCString = await _cache.GetValue(city);
if (!string.IsNullOrEmpty(cachedTemperatureCString))
{
temperatureC = Convert.ToInt32(cachedTemperatureCString);
}
else
{
temperatureC = _weather.GetForecast(city);
await _cache.SetValue(city, temperatureC.ToString());
}
var forecast = new WeatherForecast(
city, DateTime.UtcNow, temperatureC);
return forecast;
}
}
}
Dockerfile Docker.
FROM mcr.microsoft.com/dotnet/aspnet:5.0-buster-slim AS base
WORKDIR /app
EXPOSE 80
FROM mcr.microsoft.com/dotnet/sdk:5.0-buster-slim AS build
WORKDIR /src
COPY ["WebApiFromDocker/WebApiFromDocker.csproj", "WebApiFromDocker/"]
RUN dotnet restore "WebApiFromDocker/WebApiFromDocker.csproj"
COPY . .
WORKDIR "/src/WebApiFromDocker"
RUN dotnet build "WebApiFromDocker.csproj" -c Release -o /app/build
FROM build AS publish
RUN dotnet publish "WebApiFromDocker.csproj" -c Release -o /app/publish
FROM base AS final
WORKDIR /app
COPY --from=publish /app/publish .
ENTRYPOINT ["dotnet", "WebApiFromDocker.dll"]
, mynet
docker network connect mynet WebApiFromDocker
Luego nos aseguraremos de que todos los contenedores necesarios estén en la misma red
docker network inspect mynet
A continuación, instalaremos Breakpoint en un método de controlador único y enviaremos una solicitud a través de Postman o cualquier navegador.
http://localhost:49156/api/weatherforecast/moscow
Por cierto, el puerto utilizado en tu caso puede diferir y puedes verlo en la ventana Contenedores.
Resultado en la ventana del cartero
Además, asegúrese de que el valor esté comprometido con redis conectándose mediante la consola redis-cli
Ok, ¡todo funcionó según lo previsto!