[
  {
    "path": ".dockerignore",
    "content": ".dockerignore\n.git\n.gitignore\n.prettierrc\n**/node_modules\n\n"
  },
  {
    "path": ".gitignore",
    "content": "node_modules\nnpm-debug.log\nclient/src/compiled/\nserver/.env\n"
  },
  {
    "path": ".prettierrc",
    "content": "singleQuote: true\n"
  },
  {
    "path": "Dockerfile",
    "content": "\n# Setup and build the client\n\nFROM node:9.4.0-alpine as client\n\nWORKDIR /usr/app/client/\nCOPY client/package*.json ./\nRUN npm install -qy\nCOPY client/ ./\nRUN npm run build\n\n\n# Setup the server\n\nFROM node:9.4.0-alpine\n\nWORKDIR /usr/app/\nCOPY --from=client /usr/app/client/build/ ./client/build/\n\nWORKDIR /usr/app/server/\nCOPY server/package*.json ./\nRUN npm install -qy\nCOPY server/ ./\n\nENV PORT 8000\n\nEXPOSE 8000\n\nCMD [\"npm\", \"start\"]\n"
  },
  {
    "path": "README.md",
    "content": "# Node + Create React App + Docker Compose\n\nA project that runs a Node server and a create-react-app app via two separate containers, using Docker Compose.\n\n## Development\n\n```\ndocker-compose up\n```\n\nFor development, the `server/` and `client/` directories have their own docker containers, which are configured via the `docker-compose.yml` file.\n\nThe client server is spun up at `localhost:3000` and it proxies internally to the server using the linked name as `server:8080`.\n\nThe local directories are mounted into the containers, so changes will reflect immediately. However, changes to package.json will likely need to a rebuild: `docker-compose down && docker-compose build && docker-compose up`.\n\n### Notes\n\n#### Adding new scss files\n\nIn a previous version of this, you needed to restart the client for new scss files to be recognized by the watch command. This may have changed (TODO: test if this still matters with react-scripts updates):\n\n```\ndocker-compose restart client\n```\n\n#### Installing npm dependencies\n\nAll changes to `node_modules` should happen _inside_ the containers. Install any new dependencies by inside the container. You can do this via `docker-compose run`, but it’s easier to just upadte a running container and avoid having to rebuild everything:\n\n```\ndocker-compose exec client\n```\n\nThen inside:\n\n```\nnpm install --save <new_dependency>\n```\n\n## Production\n\n```\ndocker-compose -f docker-compose.prod.yml up\n```\n\nFor production, this uses the Dockerfile at the root of the repo. It creates a static build of the client React app and runs Express inside server, which handles both the API and serving of React files.\n\nAs a result, different code is executing to serve the React files, but all of the API calls should remain the same. The difference between development and production isn’t ideal, but it does offer the simplicity of having the entire app run in one server on one machine.\n\nThis is one of multiple ways a Node + React app could be setup, as suggested [here](https://daveceddia.com/create-react-app-express-production/):\n\n- **Keep them together** - have Express serve both the API and React files\n- **Split them apart** - have Express API on one machine and the React files on another (e.g., on S3 and use CORS to access the API)\n- **Put the API behind a proxy** - use something like NGINX to proxy the Express API server and React static files separately\n\nThis project uses the “keep them together” approach. For better performance, you can set up a proxy (like Cloudflare) in between your server and the Internet to cache the static files. Or with some extra work you can fashion it to do either of the other two options.\n\n## Notes\n\n### Using docker compose\n\nI have `comp` aliased to `docker-compose` on my computer.\n\nStart via:\n\n```\ncomp up\n\n# or detached\ncomp up -d\n```\n\nRun a container of the server image via:\n\n```\ncomp run server /bin/bash\n```\n\nCheck status:\n\n```\ncomp ps\n```\n\nStop:\n\n```\ncomp down\n```\n\nRun the production image:\n\n```\ncomp -f docker-compose.prod.yml up\n```\n\nNOTE: if any dependencies change in package.json files, you probably will need to rebuild the container for the changes to appear, e.g.,\n\n```\ncomp down\ncomp build\ncomp up\n```\n\n### Setup references\n\nReferences for setting up a Node project with Docker and docker-compose:\n\n- https://nodejs.org/en/docs/guides/nodejs-docker-webapp/\n- https://blog.codeship.com/using-docker-compose-for-nodejs-development/\n- http://jdlm.info/articles/2016/03/06/lessons-building-node-app-docker.html\n\nExpress + React:\n\n- https://daveceddia.com/create-react-app-express-production/\n- http://ericsowell.com/blog/2017/5/16/create-react-app-and-express\n- https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0\n- https://medium.freecodecamp.org/how-to-host-a-website-on-s3-without-getting-lost-in-the-sea-e2b82aa6cd38\n"
  },
  {
    "path": "client/.dockerignore",
    "content": "node_modules\nnpm-debug.log*\n\n"
  },
  {
    "path": "client/.gitignore",
    "content": "# See https://help.github.com/ignore-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n\n# testing\n/coverage\n\n# production\n/build\n\n# misc\n.DS_Store\n.env.local\n.env.development.local\n.env.test.local\n.env.production.local\n\nnpm-debug.log*\nyarn-debug.log*\nyarn-error.log*\n"
  },
  {
    "path": "client/Dockerfile",
    "content": "FROM node:12.10.0\n\nWORKDIR /usr/app\n\nCOPY package*.json ./\n\nRUN npm ci -qy\n\nCOPY . .\n\nEXPOSE 3000\n\nCMD [\"npm\", \"start\"]\n"
  },
  {
    "path": "client/README.md",
    "content": "This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).\n\nIn dev, you can access the dev server for this. In production, this is container is built to static files and that output is packaged in the server container.\n\nYou can find more Create React App info\n[here](https://github.com/facebook/create-react-app/blob/v3.1.2/packages/react-scripts/template/README.md).\n"
  },
  {
    "path": "client/package.json",
    "content": "{\n  \"name\": \"ui\",\n  \"version\": \"0.2.0\",\n  \"private\": true,\n  \"dependencies\": {\n    \"react\": \"^16.9.0\",\n    \"react-dom\": \"^16.9.0\",\n    \"react-scripts\": \"^3.1.2\"\n  },\n  \"scripts\": {\n    \"start\": \"react-scripts start\",\n    \"build\": \"react-scripts build\",\n    \"test\": \"react-scripts test --env=jsdom\",\n    \"eject\": \"react-scripts eject\"\n  },\n  \"proxy\": \"http://server:8080\",\n  \"browserslist\": {\n    \"production\": [\n      \">0.2%\",\n      \"not dead\",\n      \"not op_mini all\"\n    ],\n    \"development\": [\n      \"last 1 chrome version\",\n      \"last 1 firefox version\",\n      \"last 1 safari version\"\n    ]\n  },\n  \"devDependencies\": {\n    \"sass\": \"^1.23.7\"\n  }\n}\n"
  },
  {
    "path": "client/public/index.html",
    "content": "<!DOCTYPE html>\n<html lang=\"en\">\n  <head>\n    <meta charset=\"utf-8\">\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\n    <meta name=\"theme-color\" content=\"#000000\">\n    <!--\n      manifest.json provides metadata used when your web app is added to the\n      homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/\n    -->\n    <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\">\n    <link rel=\"shortcut icon\" href=\"%PUBLIC_URL%/favicon.ico\">\n    <!--\n      Notice the use of %PUBLIC_URL% in the tags above.\n      It will be replaced with the URL of the `public` folder during the build.\n      Only files inside the `public` folder can be referenced from the HTML.\n\n      Unlike \"/favicon.ico\" or \"favicon.ico\", \"%PUBLIC_URL%/favicon.ico\" will\n      work correctly both with client-side routing and a non-root public URL.\n      Learn how to configure a non-root public URL by running `npm run build`.\n    -->\n    <title>React App</title>\n  </head>\n  <body>\n    <noscript>\n      You need to enable JavaScript to run this app.\n    </noscript>\n    <div id=\"root\"></div>\n    <!--\n      This HTML file is a template.\n      If you open it directly in the browser, you will see an empty page.\n\n      You can add webfonts, meta tags, or analytics to this file.\n      The build step will place the bundled scripts into the <body> tag.\n\n      To begin the development, run `npm start` or `yarn start`.\n      To create a production bundle, use `npm run build` or `yarn build`.\n    -->\n  </body>\n</html>\n"
  },
  {
    "path": "client/public/manifest.json",
    "content": "{\n  \"short_name\": \"React App\",\n  \"name\": \"Create React App Sample\",\n  \"icons\": [\n    {\n      \"src\": \"favicon.ico\",\n      \"sizes\": \"64x64 32x32 24x24 16x16\",\n      \"type\": \"image/x-icon\"\n    }\n  ],\n  \"start_url\": \"./index.html\",\n  \"display\": \"standalone\",\n  \"theme_color\": \"#000000\",\n  \"background_color\": \"#ffffff\"\n}\n"
  },
  {
    "path": "client/src/components/App.js",
    "content": "import React, { Component } from 'react';\n\nimport logo from './logo.svg';\n\nimport './App.scss';\n\nclass App extends Component {\n  constructor() {\n    super();\n\n    this.state = {};\n  }\n\n  componentDidMount() {\n    this.callApi()\n      .then(res => this.setState(res))\n      .catch(console.error);\n  }\n\n  callApi = async () => {\n    const resp = await fetch('/api');\n\n    window._resp = resp;\n\n    let text = await resp.text();\n\n    let data = null;\n    try {\n      data = JSON.parse(text); // cannot call both .json and .text - await resp.json();\n    } catch (e) {\n      console.err(`Invalid json\\n${e}`);\n    }\n\n    if (resp.status !== 200) {\n      throw Error(data ? data.message : 'No data');\n    }\n\n    return data;\n  };\n\n  render() {\n    return (\n      <div className=\"App\">\n        <header className=\"App-header\">\n          <img src={logo} className=\"App-logo\" alt=\"logo\" />\n          <h1 className=\"App-title\">Welcome to React</h1>\n        </header>\n        <p className=\"App-intro\">\n          To get started, edit <code>src/App.js</code> and save to reload.\n        </p>\n        <p>{this.state.message || 'No message'}</p>\n      </div>\n    );\n  }\n}\n\nexport default App;\n"
  },
  {
    "path": "client/src/components/App.scss",
    "content": ".App {\n  text-align: center;\n}\n\n.App-logo {\n  animation: App-logo-spin infinite 20s linear;\n  height: 80px;\n}\n\n.App-header {\n  background-color: #222;\n  height: 150px;\n  padding: 20px;\n  color: white;\n}\n\n.App-title {\n  font-size: 1.5em;\n}\n\n.App-intro {\n  font-size: large;\n}\n\n@keyframes App-logo-spin {\n  from {\n    transform: rotate(0deg);\n  }\n  to {\n    transform: rotate(360deg);\n  }\n}\n"
  },
  {
    "path": "client/src/components/App.test.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nit('renders without crashing', () => {\n  const div = document.createElement('div');\n  ReactDOM.render(<App />, div);\n});\n"
  },
  {
    "path": "client/src/index.js",
    "content": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport App from './components/App';\nimport registerServiceWorker from './registerServiceWorker';\n\nimport './index.scss';\n\nReactDOM.render(<App />, document.getElementById('root'));\n\nregisterServiceWorker();\n"
  },
  {
    "path": "client/src/index.scss",
    "content": "body {\n  margin: 0;\n  padding: 0;\n  font-family: sans-serif;\n}\n"
  },
  {
    "path": "client/src/registerServiceWorker.js",
    "content": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on subsequent visits in production, and gives\n// it offline capabilities. However, it also means that developers (and users)\n// will only see deployed updates on the \"N+1\" visit to a page, since previously\n// cached resources are updated in the background.\n\n// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.\n// This link also includes instructions on opting out of this behavior.\n\nconst isLocalhost = Boolean(\n  window.location.hostname === 'localhost' ||\n    // [::1] is the IPv6 localhost address.\n    window.location.hostname === '[::1]' ||\n    // 127.0.0.1/8 is considered localhost for IPv4.\n    window.location.hostname.match(\n      /^127(?:\\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/\n    )\n);\n\nexport default function register() {\n  if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {\n    // The URL constructor is available in all browsers that support SW.\n    const publicUrl = new URL(process.env.PUBLIC_URL, window.location);\n    if (publicUrl.origin !== window.location.origin) {\n      // Our service worker won't work if PUBLIC_URL is on a different origin\n      // from what our page is served on. This might happen if a CDN is used to\n      // serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374\n      return;\n    }\n\n    window.addEventListener('load', () => {\n      const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;\n\n      if (isLocalhost) {\n        // This is running on localhost. Lets check if a service worker still exists or not.\n        checkValidServiceWorker(swUrl);\n      } else {\n        // Is not local host. Just register service worker\n        registerValidSW(swUrl);\n      }\n    });\n  }\n}\n\nfunction registerValidSW(swUrl) {\n  navigator.serviceWorker\n    .register(swUrl)\n    .then(registration => {\n      registration.onupdatefound = () => {\n        const installingWorker = registration.installing;\n        installingWorker.onstatechange = () => {\n          if (installingWorker.state === 'installed') {\n            if (navigator.serviceWorker.controller) {\n              // At this point, the old content will have been purged and\n              // the fresh content will have been added to the cache.\n              // It's the perfect time to display a \"New content is\n              // available; please refresh.\" message in your web app.\n              console.log('New content is available; please refresh.');\n            } else {\n              // At this point, everything has been precached.\n              // It's the perfect time to display a\n              // \"Content is cached for offline use.\" message.\n              console.log('Content is cached for offline use.');\n            }\n          }\n        };\n      };\n    })\n    .catch(error => {\n      console.error('Error during service worker registration:', error);\n    });\n}\n\nfunction checkValidServiceWorker(swUrl) {\n  // Check if the service worker can be found. If it can't reload the page.\n  fetch(swUrl)\n    .then(response => {\n      // Ensure service worker exists, and that we really are getting a JS file.\n      if (\n        response.status === 404 ||\n        response.headers.get('content-type').indexOf('javascript') === -1\n      ) {\n        // No service worker found. Probably a different app. Reload the page.\n        navigator.serviceWorker.ready.then(registration => {\n          registration.unregister().then(() => {\n            window.location.reload();\n          });\n        });\n      } else {\n        // Service worker found. Proceed as normal.\n        registerValidSW(swUrl);\n      }\n    })\n    .catch(() => {\n      console.log(\n        'No internet connection found. App is running in offline mode.'\n      );\n    });\n}\n\nexport function unregister() {\n  if ('serviceWorker' in navigator) {\n    navigator.serviceWorker.ready.then(registration => {\n      registration.unregister();\n    });\n  }\n}\n"
  },
  {
    "path": "docker-compose.prod.yml",
    "content": "version: '2'\nservices:\n  web:\n    build: .\n    ports:\n      - \"80:8000\"\n    restart: always\n    # env_file: ./server/.env # TODO - uncomment this to auto-load your .env file!\n    environment:\n      NODE_ENV: production\n      PORT: 8000\n"
  },
  {
    "path": "docker-compose.yml",
    "content": "version: '2'\nservices:\n  server:\n    build:\n      context: ./server/\n    command: /usr/app/node_modules/.bin/nodemon src/index.js\n    volumes:\n      - ./server/:/usr/app\n      - /usr/app/node_modules\n    ports:\n      - \"8080:8080\"\n    # env_file: ./server/.env # TODO - uncomment this to auto-load your .env file!\n    environment:\n      - NODE_ENV=development\n      - CHOKIDAR_USEPOLLING=true\n  client:\n    build:\n      context: ./client/\n    command: npm start\n    volumes:\n      - ./client/:/usr/app\n      - /usr/app/node_modules\n    depends_on:\n      - server\n    ports:\n      - \"3000:3000\"\n"
  },
  {
    "path": "server/.dockerignore",
    "content": "node_modules\nnpm-debug.log*\n\n"
  },
  {
    "path": "server/.gitignore",
    "content": "# dependencies\n/node_modules\n\nnpm-debug.log*\n"
  },
  {
    "path": "server/Dockerfile",
    "content": "FROM node:12.10.0-alpine\n\nWORKDIR /usr/app\n\nCOPY package*.json ./\nRUN npm ci -qy\n\nCOPY . .\n\nEXPOSE 8080\n\nCMD [\"npm\", \"start\"]\n"
  },
  {
    "path": "server/package.json",
    "content": "{\n  \"name\": \"node-react-docker-compose\",\n  \"version\": \"1.0.0\",\n  \"description\": \"A reference for running a node server and create-react-app app via docker-compose.\",\n  \"main\": \"src/index.js\",\n  \"scripts\": {\n    \"start\": \"node src/index.js\",\n    \"test\": \"echo \\\"Error: no test specified\\\" && exit 1\"\n  },\n  \"author\": \"Peter Coles\",\n  \"license\": \"MIT\",\n  \"dependencies\": {\n    \"express\": \"^4.17.1\"\n  },\n  \"devDependencies\": {\n    \"nodemon\": \"^1.19.0\"\n  }\n}\n"
  },
  {
    "path": "server/src/index.js",
    "content": "'use strict';\n\nconst express = require('express');\nconst path = require('path');\n\n// Constants\nconst PORT = process.env.PORT || 8080;\nconst HOST = '0.0.0.0';\n\nconst CLIENT_BUILD_PATH = path.join(__dirname, '../../client/build');\n\n// App\nconst app = express();\n\n// Static files\napp.use(express.static(CLIENT_BUILD_PATH));\n\n// API\napp.get('/api', (req, res) => {\n  res.set('Content-Type', 'application/json');\n  let data = {\n    message: 'Hello world, Woooooeeeee!!!!'\n  };\n  res.send(JSON.stringify(data, null, 2));\n});\n\n// All remaining requests return the React app, so it can handle routing.\napp.get('*', function(request, response) {\n  response.sendFile(path.join(CLIENT_BUILD_PATH, 'index.html'));\n});\n\napp.listen(PORT, HOST);\nconsole.log(`Running on http://${HOST}:${PORT}`);\n"
  }
]