php - Why i get 502 BagGateway error on my nginx server?

one text

I am using docker with php and nginx to create server to print hello world with php script on localhost. I Here are my files:

  • nginx dockerfile:
FROM nginx:1.17.8-alpine

# Copy the public directory
# COPY ./public/ /app/public/
COPY . /app/

# Copy the nginx config file
COPY ./docker/nginx/nginx.conf /etc/nginx/conf.d/default.conf
  • nginx.conf:
server {
    listen 80 default_server;
    listen [::]:80 default_server;
    server_name _;
    server_tokens off;

    root /app/;
    index index.php;

    location / {
        try_files $uri $uri/ /index.php$is_args$args;
    }

    location ~ \.php$ {
        include fastcgi_params;
        fastcgi_pass php:9000;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

-php dockerfile:

FROM php:7.4.3-fpm-alpine3.11

COPY . /app

VOLUME ["/app"]
  • docker-compose.yml:
version: '3'

services:
  web:
    build:
      context: .
      dockerfile: docker/nginx/Dockerfile
    ports:
      - "8080:80"
    volumes:
      - .:/app/
    links:
      - php

  php:
    build:
      context: .
      dockerfile: docker/php/Dockerfile
    volumes:
      - .:/app/
  • index.php:
<?php

echo 'Hellow World!!';

When i run docker and try to open localhost::8080 i get this error:

web_1 | 2022/11/07 23:37:59 \[error\] 7#7: \*1 connect() failed (111: Connection refused) while connecting to upstream, client:, server: \_, request: "GET / HTTP/1.1", upstream: "fastcgi://", host:"localhost:8080"

web_1 | 172.18.0.1 - - \[07/Nov/2022:23:37:59 +0000\] "GET / HTTP/1.1" 502 552 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-"

web_1 | 2022/11/07 23:37:59 \[error\] 7#7: \*1 connect() failed (111: Connection refused) while connecting to upstream, client:, server: \_, request: "GET /favicon.ico HTTP/1.1", upstream: "fastcgi://", host: "localhost:8080", referrer: "http://localhost:8080/"

web_1 |- - \[07/Nov/2022:23:37:59 +0000\] "GET /favicon.ico HTTP/1.1" 502 552 "http://localhost:8080/" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/107.0.0.0 Safari/537.36" "-"

I expect to see result of php script on localhost server. I tried to add following string to nginx conf but i did not help fastcgi_pass unix:/var/run/php5-fpm.sock;.

Source