How to connect two Docker containers running react and python

Viewed 493

I have docker-compose.yml to bring up two docker containers.

1.) front-end - reactjs - running on port 3000

2.) back-end - python (flask) - running on port 8083

The front-end is calling the python server for a POST method through the url "http://127.0.0.1:8083/api using axios, but now since these are running at two containers, how can I connect the front-end to the python server through that url?

This is my docker-compose.yml

version: "3.2"

services:

  frontend:
    build: ./frontend
    environment:
      CHOKIDAR_USEPOLLING: "true"
    volumes:
      - /app/node_modules
      - ./frontend:/app
    ports:
      - 80:3000
    depends_on: 
      - backend

  backend: 
    build: ./backends/jananath
    volumes:
      - ./backends/jananath:/usr/src/app
    environment:
      FLASK_APP: /usr/src/app/server.py
      FLASK_DEBUG: 1
      FLASK_RUN_EXTRA_FILES: "/usr/src/app/banuka.txt"
    ports: 
      - 5000:8083

And this is the server.py python server

from flask import Flask, render_template, request, url_for, redirect
import os
from os import path, walk
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

PORT = 8083

@app.route('/api', methods=['POST', 'GET'])
def upload_file():
    file = request.files['file']
    filename = file.filename

    print(filename)

    filepath = os.path.abspath(filename)
    print(filepath)
    response_ = {}
    response_['filename'] = str(filename)
    response_['filepath'] = str(filepath)
    return response_


if __name__ == '__main__':
    app.run(host='0.0.0.0', port=PORT, extra_files=extra_files)

And this is the axios calling a POST method from front-end to this server.py

const onFormSubmit = async (e) => {
    e.preventDefault();

    const formData = new FormData();
    formData.append("file", file);

    try {

      const res = await axios.post("http://127.0.0.1:8083/api", formData, { // this url should change now?
        headers: {
          "Content-Type": "multipart/form-data",
          "Access-Control-Allow-Credentials": "true",
          "crossorigin": "true",
        },
      });

      const {filename, filepath} = res.data;

      setUploadedFile({filename, filepath});
    } catch (error) {
      console.log(error);
    }
  };

I think the problem here is the URL is now changed, but I don't know how to fix that. Can someone tell me how to fix this and what is the correct URL I should hit?

Thank you!

1 Answers

try backend:8083 in your react app, you will need to rebuild your react image.

Related