There are many different ways to create Docker images for your AspNet Core applications.
Often, developers wonder why their containerized application doesn’t receive requests within Docker and there are a few misconceptions about
EXPOSE, port mapping and the AspNetCore ports.
There are 3 levels we have to consider:
EXPOSE instruction exposes ports for use within links. This means that it makes a service non accessible from outside Docker, but it is accessible inside other Docker containers. It’s like half way there, but for some scenarios it may be enough.
AspNetCore Urls environment variable
EXPOSE a port where you want your AspNetCore application to receive requests, but that does not mean these ports match the port that the AspNetCore is listening on.
Let’s assume you want your docker container to expose the port 8080. You would add this to the Dockerfile
But that would not be enough to reach the AspNetCore application if the port does not match. Therefore you need to add an environment variable to the Dockerfile to configure AspNetCore to run on that port.
Now both ports match, but still we need something else if we want to spin up a container with that image and access our AspNetCore application within that container from our host.
When running the container, we need to map the container exposed port with the localhost port we want to use with the argument
p <local_port>:<docker_exposed_port>. By default, Docker will expose whichever port we specify in the mapping but, again, that does not mean that our AspNetCore application’s port matches it unless we configure the AspNetCore Urls environment variable.
As an example, if we know that a specific image exposes port 8080 and we want to map it to our port 5000 we would do the following.
docker run -p 5000:8080 registry.gitlab.com/sunnyatticsoftware/my-sample-asp-net-core:latest