开发者

How to make JavaScript fetch request from a react app docker container to a Rails API docker container within the same network?

I have a couple of docker containers within a network. A container with a frontend react project and another container with a Rails API. I'm looking to make a request from the react project container to the Rails API but the fetch API continues to run into this error:

net::ERR_NAME_NOT_RESOLVED


React Code

function App() {

...
  async function apiRequest() {
    const options = {
      headers: myHeaders,
      method: requestMethod,
    }

    formData.append('username',username);
    formData.append('password',password);

    if (requestMethod === "POST") {
      options.body = formData
    }

    let requestStr = "http://user-api:3000/api/users/";
    let apiRequest = await fetch(requestStr, options)
    let data = await apiRequest.json()
    console.log(data)
  }
...
}

Dockerfile Frontend (React app using Vite)

FROM node
WORKDIR /app
COPY package.json .
RUN npm i
COPY . .
EXPOSE 5000
CMD ["npm", "run", "dev"]

Dockerfile Rails API

FROM ruby:2.7.1

ENV APP_HOME /rails-docker
# Installation of dependencies
RUN apt-get update -qq \
  && apt-get install -y \
      # Needed for certain gems
    build-essential \
         # Needed for postgres gem
    libpq-dev \
    # The following are used to trim down the size of the image by removing unneeded data
  && apt-get clean autoclean \
  && apt-get autoremove -y \
  && rm -rf \
    /var/lib/apt \
    /var/lib/dpkg \
    /var/lib/cache \
    /var/lib/log
# Create a directory for our application
# and set it as the working directory
RUN mkdir $APP_HOME
WORKDIR $APP_HOME
# Add our Gemfile and install gems
ADD Gemfile* $APP_HOME/
RUN bundle install
# Copy over our application code
ADD . $APP_HOME
# Run our app
CMD RAILS_ENV=${RAILS_ENV} bundle exec rails db:create db:migrate db:seed && bundle exec rails s -p ${PORT} -b '0.0.0.0'

Docker-compose.yml

version: '3.8'

services:
  db:
    container_name: movie-db
    image: postgres
    environment: 
      POSTGRES_USER: root
      POSTGRES_PASSWORD: mysecretpassword
    ports:
      - "5432:5432"
    volumes:
      - postgres:/var/lib/postgresql/data

  frontend:
    container_name: movie-dojo-front开发者_JS百科end
    build: ./movie_dojo
    image: "josephse91/movie-dojo-frontend"
    ports: 
      - "5000:5000"
  user-api:
    container_name: user-api
    build: ./user_api
    image: "josephse91/rails_api"
    command: bash -c "rm -f tmp/pids/server.pid && bundle exec rails s -b '0.0.0.0'"
    volumes:
      - .:/Rails-Docker
    ports:
      - "3000:3000"
    depends_on:
      - db
    tty: true
    stdin_open: true

volumes:
  postgres:

networks:
  default:
    name: "movie-dojo-network"

I've tried to place the rails API container name as the host within the fetch call but I haven't had any luck. Any advice?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜