1
0
Fork 0
mirror of https://github.com/docker/awesome-compose.git synced 2025-04-26 10:43:35 +02:00

react-express-mongodb: rename server to backend

The goal here is to keep the same structure than the other examples.
Also, considering that it has a "frontend" folder, the equivalent for
the server should be "backend".

Signed-off-by: Jérémie Drouet <jeremie.drouet@gmail.com>
This commit is contained in:
Jérémie Drouet 2020-05-12 15:05:18 +02:00
parent e29f0d1c54
commit 9696296945
16 changed files with 8 additions and 8 deletions

View file

@ -0,0 +1,27 @@
FROM node:13.13.0-stretch-slim
#Argument that is passed from docer-compose.yaml file
ARG NODE_PORT
#Echo the argument to check passed argument loaded here correctly
RUN echo "Argument port is : $NODE_PORT"
# Create app directory
WORKDIR /usr/src/app
#COPY . .
COPY . .
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
RUN npm install
#In my case my app binds to port NODE_PORT so you'll use the EXPOSE instruction to have it mapped by the docker daemon:
EXPOSE ${NODE_PORT}
CMD npm run dev

View file

@ -0,0 +1,41 @@
#### Snippet of backend(Node.js)`DockerFile`
You will find this `DockerFile` file in the root directory of the project.
```bash
FROM node:13.13.0-stretch-slim
#Argument that is passed from docer-compose.yaml file
ARG NODE_PORT
#Echo the argument to check passed argument loaded here correctly
RUN echo "Argument port is : $NODE_PORT"
# Create app directory
WORKDIR /usr/src/app
#COPY . .
COPY . .
# Install app dependencies
# A wildcard is used to ensure both package.json AND package-lock.json are copied
# where available (npm@5+)
RUN npm install
#In my case my app binds to port NODE_PORT so you'll use the EXPOSE instruction to have it mapped by the docker daemon:
EXPOSE ${NODE_PORT}
CMD npm run dev
```
##### Explanation of backend(Node.js) `DockerFile`
- The first line tells Docker to use another Node image from the [DockerHub](https://hub.docker.com/). Were using the official Docker image for Node.js and its version 10 image.
- On second line we declare argument `NODE_PORT` which we will pass it from `docker-compose`.
- On third line we log to check argument is successfully read
- On fourth line we sets a working directory from where the app code will live inside the Docker container.
- On fifth line, we are copying/bundling our code working directory into container working directory on line three.
- On line seven, we run npm install for dependencies in container on line four.
- On Line eight, we setup the port, that Docker will expose when the container is running. In our case it is the port which we define inside `.env` file, read it from `docker-compose` then passed as a argument to the (backend)`DockerFile`.
- And in last, we tell docker to execute our app inside the container by using node to run `npm run dev. It is the command which I registered in __package.json__ in script section.
###### :clipboard: `Note: For development purpose I used __nodemon__ , If you need to deploy at production you should change CMD from __npm run dev__ to __npm start__.`

View file

@ -0,0 +1,12 @@
var env = process.env.NODE_ENV || 'development';
if(env === 'development' || env === 'test'){
const config = require('./config.json')
let envConfig = config[env];
console.log(envConfig);
Object.keys(envConfig).forEach((key) => {
process.env[key] = envConfig[key]
})
}

View file

@ -0,0 +1,10 @@
{
"test":{
"PORT": 3000,
"MONGODB_URI": "mongodb://mongo:27017/TodoAppTest"
},
"development":{
"PORT": 3000,
"MONGODB_URI": "mongodb://mongo:27017/TodoApp"
}
}

View file

@ -0,0 +1,62 @@
module.exports = {
AUTHENTICATION_FAILED: {
code: 400,
message: 'Authentication failed. Please login with valid credentials.',
success: false,
},
SUCCESSFUL_LOGIN: {
code: 200,
message: 'Successfully logged in',
success: true,
},
INTERNAL_SERVER_ERROR: {
code: 500,
message: 'Something unexpected happened',
success: false,
},
UNAUTHORIZED: {
code: 401,
message: 'You session is expired. Please login again',
success: false,
},
SUCCESSFUL_DELETE: {
code: 200,
message: 'Successfully deleted',
success: true,
},
SUCCESSFUL_UPDATE: {
code: 200,
message: 'Updated successfully',
success: true,
},
SUCCESSFUL: {
code: 200,
success: true,
message: 'Successfully completed',
},
NOT_FOUND: {
code: 404,
success: true,
message: 'Requested API not found',
},
ALREADY_EXIST: {
code: 200,
success: true,
message: 'Already exists',
},
FORBIDDEN: {
code: 403,
message: 'You are not authorized to complete this action',
success: false,
},
BAD_REQUEST: {
code: 400,
message: 'Bad request. Please try again with valid parameters',
success: false,
},
IN_COMPLETE_REQUEST: {
code: 422,
message: 'Required parameter missing',
success: false,
},
};

View file

@ -0,0 +1,30 @@
/**
* Created by Syed Afzal
*/
const mongoose = require('mongoose');
const {log} = require('../utils/helpers/logger');
exports.connect = (app) => {
const options = {
useNewUrlParser: true,
autoIndex: false, // Don't build indexes
reconnectTries: 30, // Retry up to 30 times
reconnectInterval: 500, // Reconnect every 500ms
poolSize: 10, // Maintain up to 10 socket connections
// If not connected, return errors immediately rather than waiting for reconnect
bufferMaxEntries: 0
}
const connectWithRetry = () => {
mongoose.Promise = global.Promise;
console.log('MongoDB connection with retry')
mongoose.connect(process.env.MONGODB_URI, options).then(()=>{
console.log('MongoDB is connected');
app.emit('ready');
}).catch(err=>{
console.log('MongoDB connection unsuccessful, retry after 2 seconds.')
setTimeout(connectWithRetry, 2000)
})
}
connectWithRetry();
};

Binary file not shown.

View file

@ -0,0 +1,14 @@
/**
* Created by Syed Afzal
*/
const mongoose = require('mongoose');
var Todo = mongoose.model('Todo', {
text : {
type: String,
trim: true,
required: true
}
});
module.exports = {Todo};

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,27 @@
{
"name": "docker_node_mongo_starter",
"version": "1.0.0",
"description": "docker starter with node js and mongodb services",
"main": "index.js",
"scripts": {
"start": "node server.js",
"dev": "nodemon server.js"
},
"author": "Syed Afzal",
"license": "ISC",
"dependencies": {
"bcryptjs": "^2.4.3",
"body-parser": "^1.18.2",
"cookie-parser": "^1.4.4",
"cors": "^2.8.4",
"express": "^4.17.1",
"lodash": "^4.17.13",
"mongodb": "^3.0.7",
"mongoose": "^5.0.15",
"simple-node-logger": "^18.12.23",
"validator": "^10.1.0"
},
"devDependencies": {
"nodemon": "^2.0.3"
}
}

View file

@ -0,0 +1,38 @@
const express = require('express');
const serverResponses = require('../utils/helpers/server.responses');
const messages = require('../config/messages');
var {Todo} = require('../models/todos/todo.model');
const routes = (app) => {
const router = express.Router();
router.post('/todos', (req,res)=>{
var todo = new Todo({
text: req.body.text
});
todo.save()
.then((result)=>{
serverResponses.sendSuccess(res,messages.SUCCESSFUL, result);
})
.catch((e) => {
serverResponses.sendError(res,messages.BAD_REQUEST,e)
})
});
router.get('/', (req,res) => {
Todo.find({}, {__v:0})
.then((todos)=>{
serverResponses.sendSuccess(res,messages.SUCCESSFUL, todos);
})
.catch((e) => {
serverResponses.sendError(res,messages.BAD_REQUEST,e)
})
});
//it's a prefix before api it is useful when you have many modules and you want to
//differentiate b/w each module you can use this technique
app.use('/api', router);
};
module.exports = routes;

35
react-express-mongodb/backend/server.js vendored Normal file
View file

@ -0,0 +1,35 @@
/**
* Created by Syed Afzal
*/
require('./config/config');
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const db = require('./db');
const app = express();
//connection from db here
db.connect(app);
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
// adding routes
require('./routes')(app);
app.on('ready', () => {
app.listen(3000, () => {
console.log("Server is up on port", 3000)
});
})
module.exports = app;

View file

@ -0,0 +1,9 @@
const path = require('path');
const filename = path.join(__dirname, '../../logs/project.log');
//you can change format according to you
const log = require('simple-node-logger').createSimpleLogger( {
logFilePath:filename,
timestampFormat:'YYYY-MM-DD HH:mm:ss'}
);
module.exports = {log};

View file

@ -0,0 +1,21 @@
const serverResponse = {
sendSuccess: (res, message, data = null) => {
const responseMessage = {
code: message.code ? message.code : 500,
success: message.success,
message: message.message,
};
if (data) { responseMessage.data = data; }
return res.status(message.code).json(responseMessage);
},
sendError: (res, error) => {
const responseMessage = {
code: error.code ? error.code : 500,
success: false,
message: error.message,
};
return res.status(error.code ? error.code : 500).json(responseMessage);
},
};
module.exports = serverResponse;