skip to Main Content

I created an ASP.NET Core Web API project with docker support as follows:

Project

Each time the docker container gets created, the port mapping changes

First

…and changes…

Second

…and changes.

Third

I am not able to figure out how to set the port mapping in Visual Studio so that the container always launches with the same port mapping when I start debugging. Can anyone help?

Note: I already tried to add docker compose support but this ended up in having two mappings 8080:<random> and 8080:<what i defined> when running the docker port command – and it didn’t work.

Comment on solution

As the symptoms were really misleading for me, the following comment might help others: It was enough to run the project with DockerfileRunArguments enabled once to get rid of the duplicate port mapping issue when using docker compose!

2

Answers


  1. In your project properties add the next:

    <PropertyGroup>
        ...
        <DockerfileRunArguments>-p 5001:8080</DockerfileRunArguments>
    </PropertyGroup>
    

    It will allow you to access your web app via port 5001 during the debug
    http://localhost:5001/api/

    Just make sure that your port mapping does match to what says in the docker file with EXPOSE command.

    Here is some info about properties that you can use – https://learn.microsoft.com/en-us/visualstudio/containers/container-msbuild-properties?view=vs-2022

    Login or Signup to reply.
  2. If you’re running a single container:
    I’d recommend instead setting httpPort in the launch profile:

    "Container (Dockerfile)": {
      "commandName": "Docker",
      "launchBrowser": true,
      "launchUrl": "{Scheme}://{ServiceHost}:{ServicePort}",
      "environmentVariables": {
        "ASPNETCORE_HTTP_PORTS": "8080"
      },
      "publishAllPorts": false,
      "httpPort": 5001,
      "useSSL": false
    }
    

    This has the benefit of the launch URL also getting updated implicitly.

    If you’re running using the compose tools you can update the port bindings in docker-compose.override.yml:

    webapplication25:
      environment:
        - ASPNETCORE_ENVIRONMENT=Development
        - ASPNETCORE_HTTP_PORTS=8080
      ports:
        - "5001:8080"
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search