React app can't receive data from springboot in docker-compose

Viewed 14

I think "from backend : Hi. This is Spring speaking." should appear on the main screen(localhost) when this code is executed.

However, only "from backend :" appears in localhost.

It worked properly when "docker-compose" was not used.

below is my code and I'd like some advice.

react part
app.js

import React, {useEffect, useState} from 'react';
import axios from 'axios';

function App() {
   const [hello, setHello] = useState('')

    useEffect(() => {
        axios.get('/api/hello')
        .then(response => setHello(response.data))
        .catch(error => console.log(error))
    }, []);

    return (
        <div>
            from backend : {hello}
        </div>
    );
}

export default App;

setupProxy.js

const { createProxyMiddleware } = require('http-proxy-middleware');

module.exports = function(app) {
  app.use(
    '/api',
    createProxyMiddleware({
      target: 'http://backend:8080',
      changeOrigin: true,
    })
  );
};

dockerfile

FROM node:alpine
COPY package.json ./
RUN npm install
COPY ./ ./
CMD ["npm","run","start"]

spring-boot part IndexController.java

package com.chickenbandits.daeily.web;

import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RequiredArgsConstructor
@RestController
public class IndexController {

    @GetMapping("/api")
    public String index() {
        return "index";
    }

    @GetMapping("/api/hello")
    public String hello() { return "Hi. This is Spring speaking."; }
}

dockerfile

FROM openjdk:18
ARG JAR_FILE=*.jar
COPY build/libs/daeily-*-SNAPSHOT.jar app.jar
ENTRYPOINT ["java","-jar","app.jar"]

docker-compose.yml

version: '3'
services:
  backend:
    image: "0rdinary/daeily"
    ports:
      - "8080:8080"
  frontend:
    image: "0rdinary/daeily-front"
    ports:
      - "80:3000"
1 Answers

I believe you need to set container_name for "magic networking/DNS" to work.

version: '3'
services:
  backend:
    image: "0rdinary/daeily"
    container_name: backend <-- this
    ports:
      - "8080:8080"
  frontend:
    image: "0rdinary/daeily-front"
    container_name: frontend <-- this probably not necessary but nice to have
    ports:
      - "80:3000"

Without it, the container doesn't recognise its hostname.

Related