I’m completely new to Docker but for university purposes I needed to code a website (html, css, js) and eventually need to provide it as docker-compose configuration. I’ve watched countless hours of tutorials and questioned chat gpt extensively but every time I build an imagine and launch it used to get redirected to the nginx index.html page. Now after some more tries I’ve somehow managed to manually copy my index.html into the Docker image, but neither my styles.css nor my scripts.js are found when starting up a new container. I am completely lost at this point.
Dockerfile:
`FROM nginx:latest
RUN rm /etc/nginx/conf.d/default.conf
COPY nginx.conf /etc/nginx/conf.d/nginx.conf
COPY index.html /var/www/html/index.html
COPY styles.css /var/www/html/style.css
COPY scripts.js /var/www/html/script.js
EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]`
nginx.conf:
`server {
listen 80;
server_name test.local;
index index.html;
root /var/www/html;
}`
and my docker-compose.yml:
`version: '3'
services:
web:
image: nginx:latest
volumes:
- "./nginx.conf:/etc/nginx/conf.d/default.conf"
- "./code:/var/www/html"
ports:
- "80:80"`
Within Docker Desktop itself my logs show this error:
2023/06/30 11:09:37 [error] 20#20: *1 open() "/var/www/html/styles.css" failed (2: No such file or directory)
2023/06/30 11:09:37 [error] 21#21: *2 open() "/var/www/html/scripts.js" failed (2: No such file or directory)
2
Answers
Dockerfile:
Explanation:
default.conf
.EXPOSE
andCMD
instructions are already provided in the basenginx
image. Unless you wanna do something else, you generally shouldn’t be explicit there.docker-compose.yml:
Explanation
version
declaration can be omitted since docker-compose version3
.nginx.conf
looks fine.With your setup, the Dockerfile is completely ignored. You’re using the unmodified
nginx
image, and then trying to inject files into the container usingvolumes:
. It’s worth noting that the file paths in the Dockerfile and Compose file don’t match: thevolumes:
hide the image’s/var/www/html
directory and replace it with the host’s./code
directory, but the Dockerfile copies files out of the build-context directory and not a subdirectory.You need to tell Compose to
build:
the image; you do not need to specify theimage:
name unless you’re planning to push the image somewhere (and you definitely should not setimage: nginx
which will cause the base image to be overwritten). You should remove thevolumes:
so that you’re using the files actually built into the image.