Docker for Bootcamps
Getting started with Docker
Docker is great because it lets you do so much, but that also means there are a lot of options to configure. You can only configure what you understand, so lets take this one step at a time.
Containerize Create React App
Lets start with something easy. Let’s just put our front end in a container, start the container, and access it from our browser.
When you start your server, your architecture will look like this.
npm start
Our first goal is have an architecture that looks like this.
To start, let’s make a create react app:
$ npx create-react-app my-app; cd my-app
Make a Dockerfile in the root of your project.
# ./Dockerfile
# Start with this container from DockerHub.
FROM node:18
# This is the directory we will use within the Docker container.
WORKDIR /app
# Copy only the files we need to run our project
COPY ./package.json ./package.json
COPY ./public ./public
COPY ./src ./src
# After copying files from our local workspace to the container, we need to install dependencies inside the container.
RUN npm install
# open Docker's "firewall" to allow traffic from port 3000
EXPOSE 3000
CMD ["npm", "start"]
With that, our Create React App is containerized! We can run it in Docker, and access it from our browser. Give it a try, now. First, make sure Docker is installed. Then build it with…
$ docker build . --tag my-app:v1 --file Dockerfile
After you build, you have have an image. You can see all your images with…
$ docker image ls
The Docker application will take care of storing images locally. You can delete an image by referencing its tag…
$ docker image rm my-app:v1
Try building and deleting your image. Then, build your image again so we can run it in a container with…
$ docker run --publish 3000:3000 my-app:v1
The --publish 3000:3000
option exposes port 3000 from the Docker container to 3000 for you to access outside of the container.
You can now visit http://locahost:3000
in your browser and you will be accessing the dockerized app.
You can view running containers with…
$ docker ps
CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES
6cc9920f047b my-app:blog-1 "docker-entrypoint.s…" 27 minutes ago Up 27 minutes 3000/tcp cranky_clarke
Then you can use the CONTAINER ID to stop the container with…
$ docker stop 6cc9920f047b
…using whatever the CONTAINER ID was from docker ps
.
But, why would you want to dockerize create react app? Let’s talk about that next.