Repository: mrcoles/node-react-docker-compose
Branch: master
Commit: 3c6f51c45217
Files: 25
Total size: 15.9 KB
Directory structure:
gitextract_y96nwey0/
├── .dockerignore
├── .gitignore
├── .prettierrc
├── Dockerfile
├── README.md
├── client/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── Dockerfile
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ └── src/
│ ├── components/
│ │ ├── App.js
│ │ ├── App.scss
│ │ └── App.test.js
│ ├── index.js
│ ├── index.scss
│ └── registerServiceWorker.js
├── docker-compose.prod.yml
├── docker-compose.yml
└── server/
├── .dockerignore
├── .gitignore
├── Dockerfile
├── package.json
└── src/
└── index.js
================================================
FILE CONTENTS
================================================
================================================
FILE: .dockerignore
================================================
.dockerignore
.git
.gitignore
.prettierrc
**/node_modules
================================================
FILE: .gitignore
================================================
node_modules
npm-debug.log
client/src/compiled/
server/.env
================================================
FILE: .prettierrc
================================================
singleQuote: true
================================================
FILE: Dockerfile
================================================
# Setup and build the client
FROM node:9.4.0-alpine as client
WORKDIR /usr/app/client/
COPY client/package*.json ./
RUN npm install -qy
COPY client/ ./
RUN npm run build
# Setup the server
FROM node:9.4.0-alpine
WORKDIR /usr/app/
COPY --from=client /usr/app/client/build/ ./client/build/
WORKDIR /usr/app/server/
COPY server/package*.json ./
RUN npm install -qy
COPY server/ ./
ENV PORT 8000
EXPOSE 8000
CMD ["npm", "start"]
================================================
FILE: README.md
================================================
# Node + Create React App + Docker Compose
A project that runs a Node server and a create-react-app app via two separate containers, using Docker Compose.
## Development
```
docker-compose up
```
For development, the `server/` and `client/` directories have their own docker containers, which are configured via the `docker-compose.yml` file.
The client server is spun up at `localhost:3000` and it proxies internally to the server using the linked name as `server:8080`.
The 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`.
### Notes
#### Adding new scss files
In 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):
```
docker-compose restart client
```
#### Installing npm dependencies
All 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:
```
docker-compose exec client
```
Then inside:
```
npm install --save <new_dependency>
```
## Production
```
docker-compose -f docker-compose.prod.yml up
```
For 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.
As 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.
This is one of multiple ways a Node + React app could be setup, as suggested [here](https://daveceddia.com/create-react-app-express-production/):
- **Keep them together** - have Express serve both the API and React files
- **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)
- **Put the API behind a proxy** - use something like NGINX to proxy the Express API server and React static files separately
This 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.
## Notes
### Using docker compose
I have `comp` aliased to `docker-compose` on my computer.
Start via:
```
comp up
# or detached
comp up -d
```
Run a container of the server image via:
```
comp run server /bin/bash
```
Check status:
```
comp ps
```
Stop:
```
comp down
```
Run the production image:
```
comp -f docker-compose.prod.yml up
```
NOTE: if any dependencies change in package.json files, you probably will need to rebuild the container for the changes to appear, e.g.,
```
comp down
comp build
comp up
```
### Setup references
References for setting up a Node project with Docker and docker-compose:
- https://nodejs.org/en/docs/guides/nodejs-docker-webapp/
- https://blog.codeship.com/using-docker-compose-for-nodejs-development/
- http://jdlm.info/articles/2016/03/06/lessons-building-node-app-docker.html
Express + React:
- https://daveceddia.com/create-react-app-express-production/
- http://ericsowell.com/blog/2017/5/16/create-react-app-and-express
- https://medium.freecodecamp.org/how-to-make-create-react-app-work-with-a-node-backend-api-7c5c48acb1b0
- https://medium.freecodecamp.org/how-to-host-a-website-on-s3-without-getting-lost-in-the-sea-e2b82aa6cd38
================================================
FILE: client/.dockerignore
================================================
node_modules
npm-debug.log*
================================================
FILE: client/.gitignore
================================================
# See https://help.github.com/ignore-files/ for more about ignoring files.
# dependencies
/node_modules
# testing
/coverage
# production
/build
# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local
npm-debug.log*
yarn-debug.log*
yarn-error.log*
================================================
FILE: client/Dockerfile
================================================
FROM node:12.10.0
WORKDIR /usr/app
COPY package*.json ./
RUN npm ci -qy
COPY . .
EXPOSE 3000
CMD ["npm", "start"]
================================================
FILE: client/README.md
================================================
This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).
In 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.
You can find more Create React App info
[here](https://github.com/facebook/create-react-app/blob/v3.1.2/packages/react-scripts/template/README.md).
================================================
FILE: client/package.json
================================================
{
"name": "ui",
"version": "0.2.0",
"private": true,
"dependencies": {
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-scripts": "^3.1.2"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test --env=jsdom",
"eject": "react-scripts eject"
},
"proxy": "http://server:8080",
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"devDependencies": {
"sass": "^1.23.7"
}
}
================================================
FILE: client/public/index.html
================================================
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="theme-color" content="#000000">
<!--
manifest.json provides metadata used when your web app is added to the
homescreen on Android. See https://developers.google.com/web/fundamentals/engage-and-retain/web-app-manifest/
-->
<link rel="manifest" href="%PUBLIC_URL%/manifest.json">
<link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico">
<!--
Notice the use of %PUBLIC_URL% in the tags above.
It will be replaced with the URL of the `public` folder during the build.
Only files inside the `public` folder can be referenced from the HTML.
Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
work correctly both with client-side routing and a non-root public URL.
Learn how to configure a non-root public URL by running `npm run build`.
-->
<title>React App</title>
</head>
<body>
<noscript>
You need to enable JavaScript to run this app.
</noscript>
<div id="root"></div>
<!--
This HTML file is a template.
If you open it directly in the browser, you will see an empty page.
You can add webfonts, meta tags, or analytics to this file.
The build step will place the bundled scripts into the <body> tag.
To begin the development, run `npm start` or `yarn start`.
To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>
================================================
FILE: client/public/manifest.json
================================================
{
"short_name": "React App",
"name": "Create React App Sample",
"icons": [
{
"src": "favicon.ico",
"sizes": "64x64 32x32 24x24 16x16",
"type": "image/x-icon"
}
],
"start_url": "./index.html",
"display": "standalone",
"theme_color": "#000000",
"background_color": "#ffffff"
}
================================================
FILE: client/src/components/App.js
================================================
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.scss';
class App extends Component {
constructor() {
super();
this.state = {};
}
componentDidMount() {
this.callApi()
.then(res => this.setState(res))
.catch(console.error);
}
callApi = async () => {
const resp = await fetch('/api');
window._resp = resp;
let text = await resp.text();
let data = null;
try {
data = JSON.parse(text); // cannot call both .json and .text - await resp.json();
} catch (e) {
console.err(`Invalid json\n${e}`);
}
if (resp.status !== 200) {
throw Error(data ? data.message : 'No data');
}
return data;
};
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
<p>{this.state.message || 'No message'}</p>
</div>
);
}
}
export default App;
================================================
FILE: client/src/components/App.scss
================================================
.App {
text-align: center;
}
.App-logo {
animation: App-logo-spin infinite 20s linear;
height: 80px;
}
.App-header {
background-color: #222;
height: 150px;
padding: 20px;
color: white;
}
.App-title {
font-size: 1.5em;
}
.App-intro {
font-size: large;
}
@keyframes App-logo-spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
================================================
FILE: client/src/components/App.test.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
it('renders without crashing', () => {
const div = document.createElement('div');
ReactDOM.render(<App />, div);
});
================================================
FILE: client/src/index.js
================================================
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
import registerServiceWorker from './registerServiceWorker';
import './index.scss';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
================================================
FILE: client/src/index.scss
================================================
body {
margin: 0;
padding: 0;
font-family: sans-serif;
}
================================================
FILE: client/src/registerServiceWorker.js
================================================
// In production, we register a service worker to serve assets from local cache.
// This lets the app load faster on subsequent visits in production, and gives
// it offline capabilities. However, it also means that developers (and users)
// will only see deployed updates on the "N+1" visit to a page, since previously
// cached resources are updated in the background.
// To learn more about the benefits of this model, read https://goo.gl/KwvDNy.
// This link also includes instructions on opting out of this behavior.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
);
export default function register() {
if (process.env.NODE_ENV === 'production' && 'serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
const publicUrl = new URL(process.env.PUBLIC_URL, window.location);
if (publicUrl.origin !== window.location.origin) {
// Our service worker won't work if PUBLIC_URL is on a different origin
// from what our page is served on. This might happen if a CDN is used to
// serve assets; see https://github.com/facebookincubator/create-react-app/issues/2374
return;
}
window.addEventListener('load', () => {
const swUrl = `${process.env.PUBLIC_URL}/service-worker.js`;
if (isLocalhost) {
// This is running on localhost. Lets check if a service worker still exists or not.
checkValidServiceWorker(swUrl);
} else {
// Is not local host. Just register service worker
registerValidSW(swUrl);
}
});
}
}
function registerValidSW(swUrl) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
console.log('New content is available; please refresh.');
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
if (
response.status === 404 ||
response.headers.get('content-type').indexOf('javascript') === -1
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
================================================
FILE: docker-compose.prod.yml
================================================
version: '2'
services:
web:
build: .
ports:
- "80:8000"
restart: always
# env_file: ./server/.env # TODO - uncomment this to auto-load your .env file!
environment:
NODE_ENV: production
PORT: 8000
================================================
FILE: docker-compose.yml
================================================
version: '2'
services:
server:
build:
context: ./server/
command: /usr/app/node_modules/.bin/nodemon src/index.js
volumes:
- ./server/:/usr/app
- /usr/app/node_modules
ports:
- "8080:8080"
# env_file: ./server/.env # TODO - uncomment this to auto-load your .env file!
environment:
- NODE_ENV=development
- CHOKIDAR_USEPOLLING=true
client:
build:
context: ./client/
command: npm start
volumes:
- ./client/:/usr/app
- /usr/app/node_modules
depends_on:
- server
ports:
- "3000:3000"
================================================
FILE: server/.dockerignore
================================================
node_modules
npm-debug.log*
================================================
FILE: server/.gitignore
================================================
# dependencies
/node_modules
npm-debug.log*
================================================
FILE: server/Dockerfile
================================================
FROM node:12.10.0-alpine
WORKDIR /usr/app
COPY package*.json ./
RUN npm ci -qy
COPY . .
EXPOSE 8080
CMD ["npm", "start"]
================================================
FILE: server/package.json
================================================
{
"name": "node-react-docker-compose",
"version": "1.0.0",
"description": "A reference for running a node server and create-react-app app via docker-compose.",
"main": "src/index.js",
"scripts": {
"start": "node src/index.js",
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "Peter Coles",
"license": "MIT",
"dependencies": {
"express": "^4.17.1"
},
"devDependencies": {
"nodemon": "^1.19.0"
}
}
================================================
FILE: server/src/index.js
================================================
'use strict';
const express = require('express');
const path = require('path');
// Constants
const PORT = process.env.PORT || 8080;
const HOST = '0.0.0.0';
const CLIENT_BUILD_PATH = path.join(__dirname, '../../client/build');
// App
const app = express();
// Static files
app.use(express.static(CLIENT_BUILD_PATH));
// API
app.get('/api', (req, res) => {
res.set('Content-Type', 'application/json');
let data = {
message: 'Hello world, Woooooeeeee!!!!'
};
res.send(JSON.stringify(data, null, 2));
});
// All remaining requests return the React app, so it can handle routing.
app.get('*', function(request, response) {
response.sendFile(path.join(CLIENT_BUILD_PATH, 'index.html'));
});
app.listen(PORT, HOST);
console.log(`Running on http://${HOST}:${PORT}`);
gitextract_y96nwey0/
├── .dockerignore
├── .gitignore
├── .prettierrc
├── Dockerfile
├── README.md
├── client/
│ ├── .dockerignore
│ ├── .gitignore
│ ├── Dockerfile
│ ├── README.md
│ ├── package.json
│ ├── public/
│ │ ├── index.html
│ │ └── manifest.json
│ └── src/
│ ├── components/
│ │ ├── App.js
│ │ ├── App.scss
│ │ └── App.test.js
│ ├── index.js
│ ├── index.scss
│ └── registerServiceWorker.js
├── docker-compose.prod.yml
├── docker-compose.yml
└── server/
├── .dockerignore
├── .gitignore
├── Dockerfile
├── package.json
└── src/
└── index.js
SYMBOL INDEX (11 symbols across 3 files)
FILE: client/src/components/App.js
class App (line 7) | class App extends Component {
method constructor (line 8) | constructor() {
method componentDidMount (line 14) | componentDidMount() {
method render (line 41) | render() {
FILE: client/src/registerServiceWorker.js
function register (line 21) | function register() {
function registerValidSW (line 46) | function registerValidSW(swUrl) {
function checkValidServiceWorker (line 75) | function checkValidServiceWorker(swUrl) {
function unregister (line 102) | function unregister() {
FILE: server/src/index.js
constant PORT (line 7) | const PORT = process.env.PORT || 8080;
constant HOST (line 8) | const HOST = '0.0.0.0';
constant CLIENT_BUILD_PATH (line 10) | const CLIENT_BUILD_PATH = path.join(__dirname, '../../client/build');
Condensed preview — 25 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (18K chars).
[
{
"path": ".dockerignore",
"chars": 59,
"preview": ".dockerignore\n.git\n.gitignore\n.prettierrc\n**/node_modules\n\n"
},
{
"path": ".gitignore",
"chars": 60,
"preview": "node_modules\nnpm-debug.log\nclient/src/compiled/\nserver/.env\n"
},
{
"path": ".prettierrc",
"chars": 18,
"preview": "singleQuote: true\n"
},
{
"path": "Dockerfile",
"chars": 436,
"preview": "\n# Setup and build the client\n\nFROM node:9.4.0-alpine as client\n\nWORKDIR /usr/app/client/\nCOPY client/package*.json ./\nR"
},
{
"path": "README.md",
"chars": 3867,
"preview": "# Node + Create React App + Docker Compose\n\nA project that runs a Node server and a create-react-app app via two separat"
},
{
"path": "client/.dockerignore",
"chars": 29,
"preview": "node_modules\nnpm-debug.log*\n\n"
},
{
"path": "client/.gitignore",
"chars": 285,
"preview": "# See https://help.github.com/ignore-files/ for more about ignoring files.\n\n# dependencies\n/node_modules\n\n# testing\n/cov"
},
{
"path": "client/Dockerfile",
"chars": 120,
"preview": "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",
"chars": 419,
"preview": "This project was bootstrapped with [Create React App](https://github.com/facebookincubator/create-react-app).\n\nIn dev, y"
},
{
"path": "client/package.json",
"chars": 652,
"preview": "{\n \"name\": \"ui\",\n \"version\": \"0.2.0\",\n \"private\": true,\n \"dependencies\": {\n \"react\": \"^16.9.0\",\n \"react-dom\": "
},
{
"path": "client/public/index.html",
"chars": 1590,
"preview": "<!DOCTYPE html>\n<html lang=\"en\">\n <head>\n <meta charset=\"utf-8\">\n <meta name=\"viewport\" content=\"width=device-wid"
},
{
"path": "client/public/manifest.json",
"chars": 317,
"preview": "{\n \"short_name\": \"React App\",\n \"name\": \"Create React App Sample\",\n \"icons\": [\n {\n \"src\": \"favicon.ico\",\n "
},
{
"path": "client/src/components/App.js",
"chars": 1177,
"preview": "import React, { Component } from 'react';\n\nimport logo from './logo.svg';\n\nimport './App.scss';\n\nclass App extends Compo"
},
{
"path": "client/src/components/App.scss",
"chars": 389,
"preview": ".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-head"
},
{
"path": "client/src/components/App.test.js",
"chars": 208,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\nimport App from './App';\n\nit('renders without crashing', ()"
},
{
"path": "client/src/index.js",
"chars": 269,
"preview": "import React from 'react';\nimport ReactDOM from 'react-dom';\n\nimport App from './components/App';\nimport registerService"
},
{
"path": "client/src/index.scss",
"chars": 63,
"preview": "body {\n margin: 0;\n padding: 0;\n font-family: sans-serif;\n}\n"
},
{
"path": "client/src/registerServiceWorker.js",
"chars": 4021,
"preview": "// In production, we register a service worker to serve assets from local cache.\n\n// This lets the app load faster on su"
},
{
"path": "docker-compose.prod.yml",
"chars": 236,
"preview": "version: '2'\nservices:\n web:\n build: .\n ports:\n - \"80:8000\"\n restart: always\n # env_file: ./server/.en"
},
{
"path": "docker-compose.yml",
"chars": 594,
"preview": "version: '2'\nservices:\n server:\n build:\n context: ./server/\n command: /usr/app/node_modules/.bin/nodemon src"
},
{
"path": "server/.dockerignore",
"chars": 29,
"preview": "node_modules\nnpm-debug.log*\n\n"
},
{
"path": "server/.gitignore",
"chars": 45,
"preview": "# dependencies\n/node_modules\n\nnpm-debug.log*\n"
},
{
"path": "server/Dockerfile",
"chars": 126,
"preview": "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\", \"st"
},
{
"path": "server/package.json",
"chars": 455,
"preview": "{\n \"name\": \"node-react-docker-compose\",\n \"version\": \"1.0.0\",\n \"description\": \"A reference for running a node server a"
},
{
"path": "server/src/index.js",
"chars": 781,
"preview": "'use strict';\n\nconst express = require('express');\nconst path = require('path');\n\n// Constants\nconst PORT = process.env."
}
]
About this extraction
This page contains the full source code of the mrcoles/node-react-docker-compose GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 25 files (15.9 KB), approximately 4.6k tokens, and a symbol index with 11 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.