Error 500 in Next.js Image Optimizer After Docker Build: “connect ECONNREFUSED 127.0.0.1:9000”

I am working on a Next.js application and encountering an issue after building it in Docker. The server runs on port 9000, and the frontend runs on port 3000. The images are loaded properly in the Next.js avatar tag, but they do not appear in the Image component. Instead, I get a 500 Internal Server Error.

Error Message:

GET http://localhost:3000/_next/image?url=http%3A%2F%2F127.0.0.1%3A9000%2Fuploads%2Fpublic%2Fbanners%2F1725328558480-LoneSamuraiSekiroWallpapers.jpg&w=1920&q=75 500 (Internal Server Error)
GET http://localhost:3000/_next/image?url=http%3A%2F%2F127.0.0.1%3A9000%2Fuploads%2Fpublic%2Fprofile-pictures%2F1725328558477-SamuraAndRaven.jpg&w=1920&q=75 500 (Internal Server Error)

TypeError: fetch failed
    at node:internal/deps/undici/undici:13179:13
    at process.processTicksAndRejections (node:internal/process/task_queues:105:5)
    at async fetchExternalImage (/app/node_modules/next/dist/server/image-optimizer.js:580:17)
    ...
[cause]: Error: connect ECONNREFUSED 127.0.0.1:9000

Configuration:
Next.js next.config.js file:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
      {
        protocol: "http",
        hostname: "127.0.0.1",
        port: "9000",
        pathname: "/uploads/**",
      },
    ],
  },
};

export default nextConfig;

Image Component Usage:

<Image
  src={encodeURI(baseUrl + banner)}
  alt={`${name}'s banner`}
  objectFit="cover"
  layout="fill"
/>

Additional Information:

I can view the images directly in the browser by visiting the URLs.
The image optimizer fails with an ECONNREFUSED error when the Next.js app tries to fetch images from the backend.
Both services are running in Docker containers.

What I Have Tried:

Ensured that the server is accessible and running properly on port 9000.
Confirmed that the images load properly in the browser.

Docker-compose.yml

version: "3.8"

services:
  db:
    image: postgres:14-alpine
    container_name: postgres-freetube-container
    ports:
      - "5432:5432" # Expose PostgreSQL port
    environment:
      POSTGRES_USER: user
      POSTGRES_PASSWORD: password
      POSTGRES_DB: freetube
    volumes:
      - db_data:/var/lib/postgresql/data
    networks:
      - freetube_network

  backend:
    build:
      context: ./backend
      dockerfile: Dockerfile
    ports:
      - "9000:9000" # Expose the backend port
    environment:
      NODE_ENV: production
      DATABASE_URL: "postgresql://user:password@db:5432/freetube?schema=public" # Use the db service name as the host
      PORT: 9000
    depends_on:
      - db
    command: >
      sh -c "npx prisma migrate deploy && npm start"
    networks:
      - freetube_network

  frontend:
    build:
      context: ./freetube
      dockerfile: Dockerfile
    ports:
      - "3000:3000" # Expose the frontend port
    environment:
      NEXT_PUBLIC_API_BASE_URL: "http://backend:9000/api/" # Reference the backend service
      NEXT_PUBLIC_BASE_URL: "http://backend:9000/"
    depends_on:
      - backend
    networks:
      - freetube_network
    # env_file:
    #   - .env # Ensure the .env file is correctly referenced

volumes:
  db_data:

networks:
  freetube_network:
    driver: bridge

Question:

How can I resolve the “connect ECONNREFUSED” error in the Next.js image optimizer when fetching images from my backend server after building in Docker? Is there something wrong with the configuration or the way the containers are set up?

I think you are facing “ECONNREFUSED” error in your Next.js app because your Next.js Image component is trying to fetch images from the backend server using 127.0.0.1:9000. However, inside Docker, 127.0.0.1 refers to the container itself, not your host machine or other containers.

What you can try is to ensure that both your frontend and backend services are on the same Docker network, and then use the service name instead of 127.0.0.1 in your next.config.js and when building the image URL in your component

Like below:

/** @type {import('next').NextConfig} */
const nextConfig = {
  images: {
    remotePatterns: [
  {
        protocol: "http",
        hostname: "backend", // Use the service name here
        port: "9000",
        pathname: "/uploads/**",
      },
    ],
  },
};

export default nextConfig;

1

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật