'nginx in Docker - returns "server" directive is not allowed here

I have dockerized an Angular application with the following Dockerfile and nginx.conf. The container works fine in Docker desktop. When deploying in Kubernetes cluster, the container fails to start and gives an error saying nginx: [emerg] "server" directive is not allowed here in /etc/nginx/nginx.conf:1. What could be the issue here?

Dockerfile

FROM node:14-alpine as build
WORKDIR /app
COPY package.json ./
RUN npm install
COPY . .
RUN npm install -g @angular/cli
RUN ng config -g cli.warnings.versionMismatch false
RUN ng build --configuration=production --output-path=/dist
ENV TZ=Asia/Kolkata
RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
################
# Run in NGINX #
################
FROM nginx:alpine
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/nginx.conf
COPY --from=build /dist /usr/share/nginx/html/cfss-dashboard-ui/
CMD ["nginx", "-g", "daemon off;"]
RUN chmod -R 777 /usr/share/nginx/html/cfss-dashboard-ui/
EXPOSE 80

nginx.conf

worker_processes  2;
user              nginx;

events {
    use           epoll;
    worker_connections  8;
}

error_log         /var/log/nginx/error.log info;

http {
    server_tokens off;
    include       mime.types;
    charset       utf-8;

    access_log    /var/log/nginx/access.log  combined;

    server {
        listen   80;
        listen [::]:80;
        server_name   _;

        error_page    500 502 503 504  /50x.html;

        root /usr/share/nginx/html/cfss-dashboard-ui;
        index index.html index.htm;

        location /cfss-dashboard-ui {
          try_files $uri $uri/ /index.html =404;
        }

        location /cfss-dashboard-ui/health {
            access_log off;
            add_header 'Content-Type' 'application/json';
            return 200 '{"status":"Healthy"}';
        }
    }
}

Log when starting the container

/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration
/docker-entrypoint.sh: Looking for shell scripts in /docker-entrypoint.d/
/docker-entrypoint.sh: Launching /docker-entrypoint.d/10-listen-on-ipv6-by-default.sh
10-listen-on-ipv6-by-default.sh: info: /etc/nginx/conf.d/default.conf is not a file or does not exist
/docker-entrypoint.sh: Launching /docker-entrypoint.d/20-envsubst-on-templates.sh
/docker-entrypoint.sh: Launching /docker-entrypoint.d/30-tune-worker-processes.sh
/docker-entrypoint.sh: Configuration complete; ready for start up
2022/05/14 03:28:15 [emerg] 1#1: "server" directive is not allowed here in /etc/nginx/nginx.conf:1
nginx: [emerg] "server" directive is not allowed here in /etc/nginx/nginx.conf:1


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source