502 nginx error

i have a react application with dot net core n tier architecture. after publishing from visual studio i have attached dockerfile and nginx file to it, and tried “docker build -t app .” and “docker run -d -p 81:85 app”
though the front end loads up, i get “502 bad gateway nginx/1.21.3” error while any api calls are made.
i have also tried to use only 81 port , running “docker run -d -p 81:81app” got same 502 bad gateway error.
Also, the front end make calls to web api at http://localhost:81/api.
Any help !

This is my dockerfile :


# Build runtime image
FROM mcr.microsoft.com/dotnet/aspnet:3.1
FROM nginx
RUN rm -rf /usr/share/nginx/html/*
COPY ./appui /usr/share/nginx/
COPY nginx.conf /etc/nginx/nginx.conf
WORKDIR /app
EXPOSE 85
CMD ["nginx", "-g", "daemon off;"]

here is my nginx :


worker_processes 1;
events { worker_connections 1024; }
http {
		include  mime.types;
		index   index.html index.htm;
		include /etc/nginx/mime.types;
		sendfile on;

    # Configuration for the server
    server {
        # Running port
        listen 85;
        server_name localhost;

        root /usr/share/nginx/ClientApp/build/;
        # Add index.php to the list if you are using PHP
        index index.html index.htm;


	location ^~/api/ {
                proxy_pass http://localhost:81;
                proxy_http_version 1.1;
                proxy_set_header Upgrade $http_upgrade;
                proxy_set_header Connection keep-alive;
                proxy_set_header Host $http_host;
                proxy_cache_bypass $http_upgrade;
                proxy_buffering  off;

        }

        # Proxying the connections connections
        location / {
		try_files $uri $uri/ /index.html?$args; 
        }		
    }
}

Good evening,

I see two things that are at least strange:

  • Within the Dockerfile you have two FROM - but only the last one is used. The first FROM is not an error - but not needed/doesn’t make any sense in this case.

  • With docker run -d -p 81:85 app you forward your host’s port 81 to container’s port 85. Within the container your NginX is listening on port 85 - which is fine up to now. But also within the container you try to forward requests do /api/ to the container’s localhost:81. But within the container no one is listening to :81. To connect to host’s port 81 (=outside the container) from within the container you can use 172.17.0.1:81 (if you are running Docker on Linux) or host.docker.internal:81 (if you are running Docker on Windows) for NginX’s proxy_pass. But keep in mind that you host will forward port 81 to the container’s port 85, so you can’t have any other service running on host’s port 81…

So you either have to rethink who wants to connect to what service running where on which port - or at least describe it more detailed so others can get the picture what you want to do. :slight_smile: