LoginSignup
4
4

More than 3 years have passed since last update.

docker間のAPIアクセス(for Mac)

Posted at

フロントdockerとAPIdocker間のアクセスをする方法

例えば、nuxtとRESTAPIを使って開発をしたい場合、githubのリポジトリをフロントとAPIで分けると思います。

リポジトリ

  • front-dockerリポジトリ(nuxtでフロントのみを実装)
  • api-dockerリポジトリ(PHPやrubyなどバックエンド側のみを実装)

前提

api-dockerが localhost:10000/api で起動しているとしてlocalhost:10000/apiを叩けばレスポンスが返ってくる状態とします。

api-dockerのエンドポイント

:skull: BAD

これだと、nuxt(front-docker)からapi(api-docker)に localhost:10000/api ではアクセスできません。

localhost:10000/api

※ nuxtがdockerじゃない場合はこれでOK

:tada: GOOD

docker同士のアクセスなので、localhostの部分を http://docker.for.mac.localhost にする必要があります。

http://docker.for.mac.localhost/api

Proxyの設定

次にProxyの設定です。上記だけだとCORS(Cross-Origin Resource Sharing)で怒られます。

環境ごとにAPIのエンドポイントはかわるのでcross-envでenvファイルを用意しておく

$ yarn add cross-env
config/env.development.ts
module.exports = {
  API_HOST: 'http://docker.for.mac.localhost',
}

@nuxtjs/proxyをインストール

$ yarn add @nuxtjs/proxy

nuxt.config.tsに追記

nuxt.config.ts

const envSet = require(`./config/env.${environment}.ts`)
const API_HOST = envSet.API_HOST

const config: NuxtConfiguration = {
  ...省略

  modules: [
    '@nuxtjs/axios',
    '@nuxtjs/proxy'
  ],
  /*
   ** Axios module configuration
   ** See https://axios.nuxtjs.org/options
   */
  axios: {
    proxy: true
  },
  proxy: {
    '/api': {
      target: `${API_HOST}`,
      changeOrigin: true,
      pathRewrite: {
        '^/api/': '/api/'
      }
    }
  }

  ...省略
}
4
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
4