Solved DB connection and CORS problem when developing Laravel × Nuxt.js in Docker environment

Introduction

Using the Docker environment, I built the environment of Laravel (API server) and Nuxt.js (front). At that time, I got about two container name related errors, so I will describe that point.

Things not covered in this article

--How to build a Docker environment --How to use Laravel as an API server --API request method in Nuxt.js

Overview

--Laravel is used as API server and Nuxt.js is used as front. --Request API to Laravel using axios

DB connection problem

When I accessed the DB with Laravel, the following error occurred.

スクリーンショット 2020-12-29 22.29.16.png

After checking, in the case of Docker, it was corrected that it was necessary to change .env.

(Change before)

.env


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

(After change)

.env


DB_CONNECTION=mysql
DB_HOST=db #Make this the database container name
DB_PORT=3306
DB_DATABASE=laravel
DB_USERNAME=root
DB_PASSWORD=

I was able to confirm that I can get json safely! スクリーンショット 2020-12-29 22.43.10.png

CORS problem

From Nuxt.js, use axios to get json to Laravel. スクリーンショット 2020-12-29 22.47.13.png スクリーンショット 2020-12-29 22.47.19.png I got an error related to the proxy, so I will deal with it.

Proxy settings

Add a module.

$ yarn add @nuxtjs/proxy

On the nuxt side, access Laravel with / api.

web is the container name and 80 is the container port. (I set this to localhost: 8000 at first, so I stumbled a little)

js:nuxt.config.js


  modules: [
    "@nuxtjs/axios",
    "@nuxtjs/proxy" //add to
  ],
  axios: {
    proxy: true //add to
  },
  proxy: {
    "/api": "http://web:80" //add to
  },

I was able to get the data safely! スクリーンショット 2020-12-29 22.49.10.png

in conclusion

When developing Laravel as an API server in a Docker environment, I think that there will be other necessary parts besides the above, but if you search for that area, it will come out relatively quickly, so it was not listed much there. I wrote about this time.

Recommended Posts

Solved DB connection and CORS problem when developing Laravel × Nuxt.js in Docker environment
Install laravel/Dusk in docker environment (laravel6)
Just install Laravel8 on docker in PHP8 environment
(Basic authentication) environment variables in rails and Docker
Docker × Laravel HTTPS (SSL) communication in local environment
Points stuck when running vite + Nginx in Docker environment
Build Docker + Laravel PHP + Vue.js development environment in 5 minutes
What to do when a could not find driver appears when connecting to a DB in a Docker environment
Host specification when laravel php artisan serve in docker container
Avoid Permission Denied that occurs when developing Laravel with Docker
Exit code 1 occurs when Rails is stopped in Docker environment