Adding SSL certificates to Website to Docker - docker

I have a website that runs on ssl i.e. https, I want to deploy it to Docker Windows Containers with Docker Desktop for Windows. So I wanted to ask how can it be done, I have added the certificates to the container, and when I use
RUN powershell -NoProfile -Command certmgr.exe -add MyCert.cer -s -r localMachine trustedpublisher
It gives this error.
certmgr.exe : The term 'certmgr.exe' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try again.
So can you explain how would it be done?

certmgr.exe
needs Visual Studio so it cant be run in Containers. Following is a way to do it if it helps anyone. Add this in the docker file when you are creating the image
RUN mkdir C:\cert
#cert folder contains the certificates YourCertificate.cer & Name.pfx
ADD cert/ /cert
RUN powershell -NoProfile -Command \
certutil -addstore "Root" "C:/cert/YourCertificate.cer"
RUN powershell -NoProfile -Command \
certutil -importpfx -p "password" "C:/cert/Name.pfx"
RUN powershell -NoProfile -Command \
New-WebBinding -Name "YourWebsite" -IP "*" -Port 1234 -Protocol https
RUN powershell -NoProfile -Command \
get-item cert:\LocalMachine\MY\thumbprint-of-your-cert | New-Item 0.0.0.0!1234
1234 is the port which you can bind with your website. It will bind your website to the certificate.

Related

Gitlab CICD cannot add service

For my projects I sometimes need to unittest my code against a ms sql server.
At the moment, I created a monstrous docker image, containing all the tools I need, including the sql server.
Now this image got to about 15 GB in size, which is really not cool.
So I'm trying to use the GitLab CICD Service part (as described here https://docs.gitlab.com/ee/ci/services/index.html).
But when I'm trying to add my (custom) image as a service I keep getting the health check issue:
*** WARNING: Service runner-hrtjgacu-project-1489-concurrent-0-2ae3f3cd2099f19a-gitlab.mydomain.lcaol__windowsdockerimages__mssql-0 probably didn't start properly.
Health check error:
service "runner-hrtjgacu-project-1489-concurrent-0-2ae3f3cd2099f19a-gitlab.mydomain.local__windowsdockerimages__mssql-0-wait-for-service" health check: exit code 1
Health check container logs:
2023-01-19T09:58:09.913696500Z FATAL: No HOST or PORT found
Service container logs:
*********
Now I found something online about needing to expose the ports of the service in the Dockerfile, so I tried that, but that did not help.
This is what my MSSQL DockerFile currently looks like:
FROM mcr.microsoft.com/windows/servercore:ltsc2019
# Download Links:
ENV exe "https://go.microsoft.com/fwlink/?linkid=840945"
ENV box "https://go.microsoft.com/fwlink/?linkid=840944"
ENV sa_password="_" \
attach_dbs="[]" \
ACCEPT_EULA="Y" \
sa_password_path="C:\ProgramData\Docker\secrets\sa-password"
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
# make install files accessible
COPY start.ps1 /
WORKDIR /
RUN Invoke-WebRequest -Uri $env:box -OutFile SQL.box ; \
Invoke-WebRequest -Uri $env:exe -OutFile SQL.exe ; \
Start-Process -Wait -FilePath .\SQL.exe -ArgumentList /qs, /x:setup ; \
.\setup\setup.exe /q /ACTION=Install /INSTANCENAME=MSSQLSERVER /FEATURES=SQLEngine /UPDATEENABLED=0 /SQLSVCACCOUNT='NT AUTHORITY\System' /SQLSYSADMINACCOUNTS='BUILTIN\ADMINISTRATORS' /TCPENABLED=1 /NPENABLED=0 /IACCEPTSQLSERVERLICENSETERMS ; \
Remove-Item -Recurse -Force SQL.exe, SQL.box, setup
RUN stop-service MSSQLSERVER ; \
set-itemproperty -path 'HKLM:\software\microsoft\microsoft sql server\mssql14.MSSQLSERVER\mssqlserver\supersocketnetlib\tcp\ipall' -name tcpdynamicports -value '' ; \
set-itemproperty -path 'HKLM:\software\microsoft\microsoft sql server\mssql14.MSSQLSERVER\mssqlserver\supersocketnetlib\tcp\ipall' -name tcpport -value 1433 ; \
set-itemproperty -path 'HKLM:\software\microsoft\microsoft sql server\mssql14.MSSQLSERVER\mssqlserver\' -name LoginMode -value 2 ;
HEALTHCHECK CMD [ "sqlcmd", "-Q", "select 1" ]
EXPOSE 1433/tcp
EXPOSE 4022/tcp
EXPOSE 135/tcp
EXPOSE 1434/tcp
EXPOSE 1434/udp
CMD .\start -sa_password $env:sa_password -ACCEPT_EULA $env:ACCEPT_EULA -attach_dbs \"$env:attach_dbs\" -Verbose
And this is is my .gitlab-ci.yml file:
default:
image:
name: gitlab.mydomain.local:4567/windowsdockerimages/basicnetframeworkimage:latest
tags:
- windows
- docker
# The stages during this build
stages:
- build
build:
stage: build
script:
- echo "Hello world"
- ping mssql
- dotnet run
services:
- name: gitlab.mydomain.local:4567/windowsdockerimages/mssql
alias: mssql
Anyone who can help me get closer to the solution?
*Note, the ping mssql also fails, the container in which we run cannot find the DNS
entry
I would use an existing official image for MSSQL server (https://hub.docker.com/_/microsoft-mssql-server) and run unit tests in one container and the database in another one.

Docker Desktop for Windows can't run tagged images

I'm trying to do some basic containers in Windows. I've been using Docker on Linux for years, but this issue is new for me.
Running the command
docker build -f windowsTest3.df -t dockertest . results in a good, tagged build.
...
---> 04064df75127
Step 13/13 : ENTRYPOINT C:/BuildTools/Common7/Tools/VsDevCmd.bat
---> Using cache
---> 9e098cff37a2
Successfully built 9e098cff37a2
Successfully tagged dockertest:latest
However, attempting to run an interactive shell inside the container gives an error. The system cannot find the path specified.
Edit: Can't believe I forgot to list the command...
To start the container interactively, I'm running docker run -it dockertest, but I've also tried docker run -it dockertest cmd and variations of that.
Running docker images shows that the tagged image exists, so I can't figure out what's causing the error.
docker images
C:\Users\devuser.DESKTOP-UV8CO47\Desktop\tmp>docker images
REPOSITORY TAG IMAGE ID CREATED SIZE
dockertest latest 9e098cff37a2 41 minutes ago 12.3GB
Here are my path locations:
C:\ProgramData\DockerDesktop\version-bin;C:\Program Files\Docker\Docker\Resources\bin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\Program Files (x86)\Python37-32\Scripts\;C:\Program Files (x86)\Python37-32\;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Windows\System32\OpenSSH\;C:\Program Files\Git\cmd;C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.2\common\bin;C:\Program Files\Amazon\AWSCLI\bin\;C:\Program Files (x86)\GnuWin32\bin;C:\Program Files\CMake\bin;C:\Program Files\dotnet\;C:\Windows\Microsoft.NET\Framework\v4.0.30319;C:\ProgramData\chocolatey\bin;C:\PRQA\PRQA-Framework-2.4.0\common\bin;C:\Users\DevUser\AppData\Local\Microsoft\WindowsApps;C:\Program Files (x86)\IAR Systems\Embedded Workbench 8.2\arm\bin;C:\Program Files\Git\bin;C:\Program Files\7-Zip;C:\Program Files\nssm-2.24\win64
Here is a slightly abridged version of the dockerfile
FROM mcr.microsoft.com/windows:10.0.17763.316-amd64
# Restore the default Windows shell for correct batch processing.
SHELL ["cmd", "/S", "/C"]
# Download the Build Tools bootstrapper.
ADD https://aka.ms/vs/16/release/vs_buildtools.exe C:/tmp/vs_buildtools.exe
# Install Build Tools excluding workloads and components with known issues.
RUN C:/tmp/vs_buildtools.exe --quiet --wait --norestart --nocache \
--installPath C:\BuildTools \
--all \
--remove Microsoft.VisualStudio.Component.Windows10SDK.10240 \
--remove Microsoft.VisualStudio.Component.Windows10SDK.10586 \
--remove Microsoft.VisualStudio.Component.Windows10SDK.14393 \
--remove Microsoft.VisualStudio.Component.Windows81SDK \
|| IF "%ERRORLEVEL%"=="3010" EXIT 0
ENV chocolateyUseWindowsCompression=false
RUN powershell set-executionpolicy remotesigned
RUN powershell -Command Invoke-Expression ((New-Object Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
RUN powershell -Command Install-PackageProvider -Name chocolatey -Force
RUN powershell -command "choco install -y git"
ENTRYPOINT C:/BuildTools/Common7/Tools/VsDevCmd.bat
Please check if VsDevCmd.bat is available inside the container when it's starting, at C:/BuildTools/Common7/Tools/ path
Also as per this Doc reference
On Windows, file paths specified in the CMD instruction must use
forward slashes or have escaped backslashes \.
CMD c:\Apache24\bin\httpd.exe -w
Maybe try your ENTRYPOINT like this.
ENTRYPOINT C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat
You can also use CMD
CMD C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat
Can also try this as well but recommended is above one
ENTRYPOINT C:\BuildTools\Common7\Tools\VsDevCmd.bat

Running chocolatey in docker container fails

I have docker on windows server 2016. The Dockerfile contains some build tools to be installed via chocolatey. It fails every time when I am trying to build image from mentioned Dockerfile. The chocolatey tool is not running in container.
# Use the latest Windows Server Core image.
FROM microsoft/windowsservercore
ENV chocolateyUseWindowsCompression false
RUN powershell -Command \
iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')); \
choco feature disable --name showDownloadProgress
RUN choco install visualstudio2015professional
RUN choco install qtcreator
RUN choco install curl
RUN choco install jq
RUN choco install 7zip.install
RUN choco install jfrog-cli
RUN choco install jom
Build command here.........
C:\Program Files\Docker>docker build -t test -f Dockerfile.txt .
Sending build context to Docker daemon 54.73MB
Step 1/10 : FROM microsoft/windowsservercore
latest: Pulling from microsoft/windowsservercore
3889bb8d808b: Pull complete
fb1ebf2c42b6: Pull complete
Digest: sha256:750440935dd3ef8ea148a8e4f83a0397540a8014938ae7b59eb78211da1d5969
Status: Downloaded newer image for microsoft/windowsservercore:latest
---> 7d89a4baf66c
Step 2/10 : ENV chocolateyUseWindowsCompression false
---> Running in 8a7b1fc97da5
---> 0f3c89daf01c
Removing intermediate container 8a7b1fc97da5
Step 3/10 : RUN powershell -Command iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')); choco feature disable --name showDownloadProgress
---> Running in f7088454db37
Exception calling "DownloadString" with "1" argument(s): "Unable to connect to
the remote server"
At line:1 char:1
+ iex ((new-object net.webclient).DownloadString('https://chocolatey.or ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : WebException
choco : The term 'choco' is not recognized as the name of a cmdlet, function,
script file, or operable program. Check the spelling of the name, or if a path
was included, verify that the path is correct and try again.
At line:1 char:88
+ ... .DownloadString('https://chocolatey.org/install.ps1')); choco feature ...
+ ~~~~~
+ CategoryInfo : ObjectNotFound: (choco:String) [], CommandNotFou
ndException
+ FullyQualifiedErrorId : CommandNotFoundException
The command 'cmd /S /C powershell -Command iex ((new-object net.webclient).DownloadString('https://chocolatey.org/install.ps1')); choco feature disable --name showDownloadProgress' returned a non-zero code: 1
I had this problem a while ago. It was destroying me for some time, I could not work out why one Docker image I had was building fine while the next one was not.
I finally traced it to an issue with restricted TLS, whereby the newer Windows docker base images required TLS1.2 which is not enabled by default. You may be encountering this with your windows server core base container.
The Chocolatey documentation refers to this situation in their section about installing-with-restricted-tls.
Their fix at time of writing was to do a little musical chairs with the TLS settings before putting them back - see below
$securityProtocolSettingsOriginal = [System.Net.ServicePointManager]::SecurityProtocol
try {
# Set TLS 1.2 (3072), then TLS 1.1 (768), then TLS 1.0 (192), finally SSL 3.0 (48)
# Use integers because the enumeration values for TLS 1.2 and TLS 1.1 won't
# exist in .NET 4.0, even though they are addressable if .NET 4.5+ is
# installed (.NET 4.5 is an in-place upgrade).
[System.Net.ServicePointManager]::SecurityProtocol = 3072 -bor 768 -bor 192 -bor 48
} catch {
Write-Warning 'Unable to set PowerShell to use TLS 1.2 and TLS 1.1 due to old .NET Framework installed. If you see underlying connection closed or trust errors, you may need to do one or more of the following: (1) upgrade to .NET Framework 4.5 and PowerShell v3, (2) specify internal Chocolatey package location (set $env:chocolateyDownloadUrl prior to install or host the package internally), (3) use the Download + PowerShell method of install. See https://chocolatey.org/install for all install options.'
}
iex ((New-Object
System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
[System.Net.ServicePointManager]::SecurityProtocol = $securityProtocolSettingsOriginal
Failing that, run your container without choco using docker run --name mycontainer -d [your container id] then use an interactive shell using docker exec -it mycontainer powershell and you'll be able to run the choco install interactively to get more information about the failure.
For me this turned out to be my antivirus specifically Symantec in my case, worked as soon as it was disabled.
Did you research following from https://github.com/chocolatey/choco/issues/1055
SET chocolateyUseWindowsCompression='false' REM No spaces in the equals
#powershell -NoProfile -ExecutionPolicy Bypass -Command "iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))" && SET "PATH=%PATH%;%ALLUSERSPROFILE%\chocolatey\bin"
And closest question here: Powershell unable to connect to internet at all
I managed to install choco from web in a corp network with proxy settings.
first step is creating a proxy.ps1:
$ProxyAddress = "http://proxy:port"
[system.net.webrequest]::defaultwebproxy = New-Object system.net.webproxy($ProxyAddress)
$CredCache = [System.Net.CredentialCache]::new()
$NetCreds = [System.Net.NetworkCredential]::new("username","password","")
$CredCache.Add($ProxyAddress, "Basic", $NetCreds)
[system.net.webrequest]::defaultwebproxy.credentials = $CredCache
[system.net.webrequest]::defaultwebproxy.BypassProxyOnLocal = $true
and then in Dockfile, do it this way:
FROM mcr.microsoft.com/windows:1809-amd64 AS base
SHELL ["cmd", "/S", "/C"]
# add proxy to powershell profile for all users
ADD proxy.ps1 C:\Windows\System32\WindowsPowerShell\v1.0\profile.ps1
# Install Chocolatey
RUN powershell -ExecutionPolicy unrestricted -Command `
iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))
The key is in the error message:
"Unable to connect to the remote server"
Your Docker container doesn't have internet connectivity to download the Chocolatey install script.

DockerFile executing powershell file cannot be found

I'm attempting to get an asp.net MVC application running using docker for windows. Which I've configured to use windows containers.
I'm using VS2017 to add docker support which generates the DockerFile and the docker-compose project.
The default DockerFile consists of:
FROM microsoft/aspnet:4.6.2
ARG source
WORKDIR /inetpub/wwwroot
COPY ${source:-obj/Docker/publish} .
Creating an image configured to run IIS with .net 4.6.2
This works fine, however I need to configure SSL. Using this example (https://github.com/MicrosoftDocs/Virtualization-Documentation/blob/live/windows-container-samples/iis-https/Dockerfile) and changing my file to:
FROM microsoft/aspnet:4.6.2
ARG source
WORKDIR /inetpub/wwwroot
COPY ${source:-obj/Docker/publish} .
RUN powershell.exe -Command " \
Import-Module IISAdministration; \
$cert = New-SelfSignedCertificate -DnsName demo.contoso.com -CertStoreLocation cert:\LocalMachine\My; \
$certHash = $cert.GetCertHash(); \
$sm = Get-IISServerManager; \
$sm.Sites[\"Default Web Site\"].Bindings.Add(\"*:443:\", $certHash, \"My\", \"0\"); \
$sm.CommitChanges();"
Works fine. However this is a self-signed cert and I wish to use a cert I copy to the image that I can also install into my cert store on my own machine for it to be trusted.
I've changed the DockerFile to:
FROM microsoft/aspnet:4.6.2
ARG source
WORKDIR /inetpub/wwwroot
COPY ${source:-obj/Docker/publish} .
WORKDIR /
COPY ${source:-server.pfx} ./server.pfx
RUN powershell.exe ls;
RUN powershell.exe -executionpolicy bypass -Command " \
Import-Module WebAdministration; \
$pwd = ConvertTo-SecureString -String \"server\" -Force -AsPlainText; \
Import-PfxCertificate -CertStoreLocation \"cert:\\LocalMachine\\Root\\b455d81e2414ec1da38f4de105b98066506cf86e\" -Password $pwd -FilePath \"c:\\server.pfx\"; \
Import-PfxCertificate -CertStoreLocation \"cert:\\LocalMachine\\My\\b455d81e2414ec1da38f4de105b98066506cf86e\" -Password $pwd -FilePath \"c:\\server.pfx\"; \
$cert = Get-Item "cert:\LocalMachine\My\b455d81e2414ec1da38f4de105b98066506cf86e"; \
New-WebBinding -Name \"Default Web Site\" -Protocol \"https\" -IPAddress \"*\" -Port 443; \
New-Item \"IIS:\\SslBindings\\0.0.0.0!443\" -Value $cert;"
Which feels like it should work. The powershell ls command shows the server.pfx file sitting on the c: drive of the container. However when it runs the powershell command setting up the certificate it errors saying it cannot find the file.
I've also run into issues where I've put the powershell into an actual script file, copied it onto the container, executed it, its all gone through fine but nothing seems to have happened.
If I use this chaps docker hub image it works as expect and he's using an actual powershell file:
https://hub.docker.com/r/rgarita/aspnet-ssl/
https://github.com/rgarita/aspnet-ssl-docker/tree/master/4.6.2
I'm at a bit of a loss with this, not sure if anyone has any ideas or have already gone through pain similar to this?
Thanks in advance,
Jon

Error running erlang in Windows Container

I'm attempting to get RabbitMQ up and running inside a Windows container but without a whole lot of luck. I've copied into the container the installation directories for RabbitMQ and Erlang but when I attempt to run erl.exe I'm told that beam.smp.dll is not able to be loaded.
PS C:\Program Files\erl8.2\bin> .\erl.exe
Unable to load emulator DLL
(C:\Program Files\erl8.2\erts-8.2\bin\beam.smp.dll)
Running the same command on the same installation directory on the host machine works just fine. I've checked that the file exists and that the checksums match. My bet is that there is some subtile difference in how the container loads the file and how the host loads the file. I'm just not sure where to even start looking.
Here is my Dockerfile which works. I can connect to RabbitMQ and the logs show it is running correctly, and I can login to the management UI using the guest/guest login from my host using IP/hostname of container.
# start with this container as the base
FROM microsoft/windowsservercore
# erlang installer download url
ENV erlang_download_url "http://erlang.org/download/otp_win64_19.3.exe"
# erlang will install to this location and rabbitmq will use this environment variable to locate it
ENV ERLANG_HOME c:\\erlang
# rabbitmq version used in download url and to rename folder extracted from zip file
ENV rabbitmq_version "3.6.9"
# rabbitmq zip package download url
ENV rabbit_download_url "https://www.rabbitmq.com/releases/rabbitmq-server/v3.6.9/rabbitmq-server-windows-$rabbitmq_version.zip"
# setup powershell options for RUN commands
SHELL ["powershell", "-Command", "$ErrorActionPreference = 'Stop'; $ProgressPreference = 'SilentlyContinue';"]
# download and install erlang using silent install option, and remove installer when done
RUN Invoke-WebRequest -Uri $env:erlang_download_url -OutFile erlang_install.exe ; \
Start-Process -Wait -FilePath .\erlang_install.exe -ArgumentList /S, /D=$env:ERLANG_HOME ; \
Remove-Item -Force erlang_install.exe
# download and extract rabbitmq, and remove zip file when done
RUN Invoke-WebRequest -Uri $env:rabbit_download_url -OutFile rabbitmq.zip ; \
Expand-Archive -Path .\rabbitmq.zip -DestinationPath "c:\\" ; \
Remove-Item -Force rabbitmq.zip
# remove version from rabbitmq folder name
RUN Rename-Item c:\rabbitmq_server-$env:rabbitmq_version c:\rabbitmq
# enable managment plugin
RUN c:\rabbitmq\sbin\rabbitmq-plugins.bat enable rabbitmq_management --offline
# tell rabbitmq where to find our custom config file
ENV RABBITMQ_CONFIG_FILE "c:\rabbitmq"
RUN ["cmd", "/c", "echo [{rabbit, [{loopback_users, []}]}].> c:\\rabbitmq.config"]
# run server when container starts - container will shutdown when this process ends
CMD "c:\rabbitmq\sbin\rabbitmq-server.bat"

Resources