Recently I have been exploring docker and docker-compose and I majorly work on MERN stack for my web apps hence this blog.
This blog will give you steps how you can setup a fully connected MERN application with ReactJS front end, Express JS as backend, Mongo as database and Node as server.
Lets get started.
Pre Requisites
- You already have installed docker, docker-compose
- You have an editor of your choice. I recommend VSCode.
App Structure
React App
I created a simple ReactApp using Official Start Page as reference. Its pretty simple. Once you have a simple react App running, all we need to do is add a “Dockerfile” and standard “.dockerignore” file as below:
Express App
Again, I created a simple express app. You can refer this link for the express app. I used standard express app and a simple database connection. For now the app don’t do anything. You can ignore the docker-compose from the link for now for the express app.
Now your both react and express app are ready with docker files.
Docker Compose
Lets create our connected e2e service layer now. This is done via docker-compose configuration. Create a file outside the two folders and have below information in it. I will explain the details.
Now lets see what the yml file is about:
- defines a version of docker-compose utility.
- defines the services to be used.
- react-app
- service to handle our react app
- specify container name
- specify image name
- build path for the app where the docker file is present
- command to run the service
- any environment variables to pass
- maps 5000 container port to 5000 outside port hence our react app will be running on port 5000.
- express-app
- service to handle our express app
- specify container name
- specify image name
- build path for the app where the docker file is present
- command to run the service
- maps 5000 container port to 5000 outside port hence our react app will be running on port 5000.
- depends on mongo to specify the starting order and have express connect to mongo via service name
- mongo
- mongo database
- specify container name
- image to be used
- maps 27017 container port to 27017 outside port
- adminmongo
- viewer for mongo database
- specifies the image name
- specify container name
- maps 1234 container port to 1234 outside port
My folder structure looks like below:
Build
docker-compose build
Run
docker-compose up -d
If all goes ok, you should be seeing below output which indicates our applications are deployed and hosted on docker now.
Note: it may be required to restart express-app so that it can reconnect to mongo service.
That’s it! You have successfully setup the MERN stack on docker. Happy coding!