You wrote you are a beginner, so first of all I'll just mention that the default configuration for the nginx image (I'll assume you're using a standard image) is to listen in port 80
.
This is why you can't map to port 3000
inside the container because there is no process that listen to this port.
Now if I understood you correctly and with the fact that you're using nginx with docker I guess you want to be able to configure the container's port (and not the host port because this is quiet trivial).
@mancini0 started a good direction, but I'll show how to do it in a more dynamic fashion.
We'll use the envsubst command which substitutes environment variables in shell format strings.
This command is available with the offical nginx image and also with the alpine version.
Now for the solution.
Step #1
write your nginx configuration in a template file - let's call it: site.template
:
server {
listen ${PORT};
server_name localhost;
location / {
root /usr/share/nginx/html;
index index.html index.htm;
}
}
Notice the PORT placeholder.
Step #2 - with docker-compose
Mount that inside the /etc/nginx/conf.d
directory and then execute the envsubst
command to use the template as a reference for default.conf
which is the file which will be used to setup the port configuration inside the container:
web:
image: nginx:alpine
volumes:
- ./site.template:/etc/nginx/conf.d/site.template
ports:
- "3000:8080"
environment:
- PORT=8080
command: /bin/sh -c "envsubst < /etc/nginx/conf.d/site.template > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
Notice that:
1. You need to execute the nginx daemon after that.
2. I used /bin/sh
and not /bin/bash
because my base image is alpine.
Step #2 (Another option) - inline docker run
If, for some reason you don't want to work with docker-compose you can use the following bash script:
#!/usr/bin/env bash
PORT=8080
TEMPLATE_DIR=$(pwd)/site.template
TEMPLATE_REMOTE_DIR=/etc/nginx/conf.d/site.template
IMAGE_NAME=nginx:alpine
echo "Starting nginx on port: $PORT ..."
docker run -p 3000:$PORT -v $TEMPLATE_DIR:$TEMPLATE_REMOTE_DIR $IMAGE_NAME \
/bin/sh -c "envsubst < $TEMPLATE_REMOTE_DIR > /etc/nginx/conf.d/default.conf && exec nginx -g 'daemon off;'"
(*) You can also write it inside your Dockerfile with the CMD
command, but I won't recommend you doing that.