LoginSignup
4
4

More than 3 years have passed since last update.

DockerでNodeとMysqlのセットアップをする。

Posted at

バックグラウンド

私は1年半ぐらいをITエンジニアに対していろいろのウェブのプロジェクトを開発しました。ドキドキ一つではなくテーマで仕事している。その時には問題がある。一番大きいの問題はアプリのバージョンが同じじゃないとかパソコンの環境が別別などの問題が大きいでした。そして新しいのクライアントから一つプロジェクトを貰いました。そのプロジェクトはDockerを使えました。Dockerを使って時前言ったの問題はあまり出てきました。そのプロジェクトがあるから。私はこのDockerを使ってNodeとMysqlのバースを勉強したいです。

インストール

始めるまえにDOCKERのインストールが必要です。DOCKER DOWNLOADでクダウンロードすることができる。

DockerでMysqlをセットアップする

↓のセットアップはMYSQLの作るのためにセットアップする。

File : docker-compose.yml

version: '3.3'
services:
  db:
    // DBのVERSIONを決める
    image: mysql:5.7
    restart: always
    // DBのデータをセットアップする
    environment:
      MYSQL_DATABASE: 'db_name'
      # Password for root access
      MYSQL_ROOT_PASSWORD: 'mysql'
    ports:
      # <Port exposed> : < MySQL Port running inside container>
      - '3306:3306'
    expose:
      # Opens port 3306 on the container
      - '3306'
      # Where our data will be persisted
    volumes:
      - my-db:/var/lib/mysql
volumes:
  my-db:
   driver: local

DockerでNodeをセットアップする

↓NodeJSのセットアップする。

File : docker-compose.yml

  # Names our volume
  node:
    build:
      context: .
      dockerfile: Dockerfile
    container_name: node-js
    volumes:
      - ./backend_node:/backend_node
    ports:
      - 3000:3000
    working_dir: "/backend_node"    
    command:
      sh -c 'npm i && nodemon'

↓のファイルは環境のためにセットアップする。

File : Dockerfile

FROM node:8-alpine

RUN npm install -g nodemon

# Create app directory
RUN mkdir -p /backend_node
WORKDIR /backend_node

COPY backend_node/package*.json ./

# Bundle app source
COPY backend_node/ .

RUN npm install

# Exports
EXPOSE 3000
CMD [ "nodemon" ]

nodeをinstallする。

初めに新しいNODEプロジェクトを作る。

ー Npm Init -y

↓のデータを自動に作る。

File : backend_node/package.json

{
  "name": "backend_node",
  "version": "1.0.0",
  "description": "Nabkend Code For data",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "repository": {
    "type": "git",
    "url": "https://github.com/andybit-okutama/benkyou_da_you.git"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.16.4"
  }
}

このプロジェクトでExpressのパッケージをインストールする。

ー npm install express --save-dev

File : backend_node/app.js

// server.js
const express = require('express');
const app = express();

 app.get('/', (req, res) => {
    return res.send('Hello world');
});

 const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
    console.log(`Server listening on port ${PORT}`);
}); 

Dockerに動くする。

docker-compose build
docker-compose up

画面のプロジェクトは「http://localhost:3000」でチェックすることができる。

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