If a gas always occupies the volume of its container, will its volume always be 22.4L at STP? According to the Avogadro's law, an equal volume of gases have a equal number  of moles (with constant pressure and temperature), therefore STP molar volume is $\pu{22.414 dm3 mol-1}$.

Think this: There is a container of volume $\pu{40 dm3}$ without any gases. I fill it with 1 mole of $\ce{O2}$ gas ($\pu{32 g}$), therefore according to the STP molar volume, the volume should be $\pu{22.414 dm3}$.

But we know that a gas always take the volume of its container. In above problem, the container volume is $\pu{40 dm3}$. So the volume of the gas should be $\pu{40 dm3}$. But why $\pu{22.414 dm3}$? I am confused with it.
According to Avogadro's law, equal volumes of gases at the same temperature and pressure have an equal number of particles. If you had one mole of particles at STP it would occupy $\pu{22.4dm3}$

However according to Boyle's law, pressure is inversely proportional to volume. Hence, by increasing the volume like you did, the vessel's pressure will decrease, thereby not making the measurement to be at STP. Hence, it will not be $\pu{22.4dm3}$.