Use ENTRYPOINT in Dockerfile
In this step, we'll learn how to use the ENTRYPOINT instruction in a Dockerfile and use a different port (9100).
-
In WebIDE, open the Dockerfile again.
-
Modify the content of the Dockerfile to:
FROM nginx
COPY index.html /usr/share/nginx/html/
COPY start.sh /start.sh
RUN chmod +x /start.sh
ENTRYPOINT ["/start.sh"]
This Dockerfile removes the environment variable and sed command. Instead, we'll handle the configuration at runtime using an ENTRYPOINT script. This makes our image more flexible.
- Create a new file named
start.sh in the same directory with the following content:
#!/bin/bash
## Set a default port if NGINX_PORT is not set
export NGINX_PORT=${NGINX_PORT:-9100}
## Replace the port in the nginx configuration
sed -i "s/listen[[:space:]]*80;/listen $NGINX_PORT;/g" /etc/nginx/conf.d/default.conf
echo "Starting Nginx on port $NGINX_PORT"
nginx -g 'daemon off;'
This script sets a default port, modifies the Nginx configuration at container startup, prints a message showing which port Nginx will run on, and then starts Nginx.
-
Save both files in WebIDE.
-
In the WebIDE terminal, rebuild the Docker image with a new tag:
docker build -t my-nginx-entrypoint .
- Run a container based on the new image. We'll set the port to 9100 using an environment variable.
docker run -d -p 9100:9100 -e NGINX_PORT=9100 --name entrypoint-container my-nginx-entrypoint
- Check the container logs to see the startup message:
docker logs entrypoint-container
You should see the message "Starting Nginx on port 9100" in the output.
- Verify that the web server is running correctly on the new port:
curl http://localhost:9100
You should see the HTML content of the index.html file displayed in the terminal.