Start learning free

LESSON 152 OF 173 · BACKEND: SHIPPING IT

Start the App

Practice

Your Dockerfile already builds an image with Java, Maven, the shop's packages and the shop packed into /app/target/shop.jar. But an image only says what is inside it. It must also say how the app starts: EXPOSE notes the port the app listens on, and CMD is the command a container runs when it starts.

Write CMD as a JSON list: each word in double quotes, separated by commas, inside [ ]. Docker then starts the program directly, not through a shell, so the stop signal of docker stop reaches it. For another app, a small Node.js server on port 5000, it would look like this:

EXPOSE 5000
CMD ["node", "server.js"]

A container has its own network. Inside it, 127.0.0.1 is the container itself, so a server in a container must listen on 0.0.0.0, every address; Spring Boot does that unless server.address says otherwise. The shop listens on port 8000, set by ENV SERVER_PORT=8000. To reach it from your computer, docker run -p publishes a port, your computer's port first, then the container's: -p 9000:5000 sends your computer's port 9000 to the container's port 5000.

When your code is done, the check prints:

$ docker build -t shop .
The image: Java 21, Maven, the packages and the shop, packed into /app/target/shop.jar
EXPOSE 8000: the app listens on port 8000 in the container (a note for whoever runs the image, it opens nothing by itself)
CMD: when the container starts, it runs java -jar target/shop.jar
JSON list form: java is the main process of the container, so the stop signal of docker stop reaches it
In the container: java runs target/shop.jar from /app, and the shop listens on port 8000, its SERVER_PORT setting (set with ENV)
$ docker run -p 8000:8000 shop
-p 8000:8000: port 8000 of your computer goes to port 8000 of the container
http://localhost:8000/ -> port 8000 of the container -> java -> target/shop.jar: the shop answers

Your task: add two strings to the array dockerfile: EXPOSE 8000, and a CMD that runs java -jar target/shop.jar as a JSON list. Then, below the array, store the command that starts a container from the image shop and publishes port 8000 in the field static String runCommand.


Assignment
Follow the Coding Tutorial to add the EXPOSE and CMD lines to the Dockerfile and write the docker run command.


Hint
A double quote inside a Java string is written \", so each word of the CMD list looks like \"java\" in your code. In -p, your computer's port comes first, then the container's.


STEP 1 OF 3
    Ctrl + Enter to check